48
\$\begingroup\$

Write a program or function that prints or returns a string of the alphanumeric characters plus underscore, in any order. To be precise, the following characters need to be output, and no more:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

When printing to stdout, an optional trailing newline after your output is permitted.

Built-in constants that contain 9 or more of the above characters are disallowed.


Shortest code in bytes wins.

This is a very simple challenge, which I believe will generate some interesting answers nevertheless.


Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=85666,OVERRIDE_USER=4162;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
5
  • 2
    \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$
    – Dennis
    Commented Jul 19, 2016 at 0:45
  • \$\begingroup\$ "Built-in constants that contain 9 or more of the above characters are disallowed" sighs in 05AB1E... \$\endgroup\$
    – Makonede
    Commented Feb 24, 2021 at 3:43
  • \$\begingroup\$ Is duplication of one char allowed? \$\endgroup\$
    – l4m2
    Commented Feb 24, 2022 at 17:42
  • \$\begingroup\$ @l4m2 No. "To be precise, the following characters need to be output, and no more." \$\endgroup\$
    – orlp
    Commented Feb 25, 2022 at 15:49
  • \$\begingroup\$ and no more can be parsed as "No more kind of chars" \$\endgroup\$
    – l4m2
    Commented Feb 25, 2022 at 15:51

106 Answers 106

1
\$\begingroup\$

C#, 85 bytes

()=>{var r="_";for(char c='/';c<'z';)r+=char.IsLetterOrDigit(++c)?c+"":"";return r;};

C# lambda where the output is a string.

A full string would be 69 bytes...

Code:

()=>{
    var r="_";
    for(char c='/';c<'z';)
        r+=char.IsLetterOrDigit(++c)?c+"":"";
    return r;
};

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PHP, 60 48 bytes

New version that's much shorter!

<?=preg_replace('/\W/','',join(range(' ','z')));

Try it on Ideone

Inspired by TimmyD's solution. Takes a range of all characters from   to z, joins them into a string, then replaces all characters that match \W (which is any character not specified in this challenge) with nothing.

Old version:

0123456789_<?php for($i=64;++$i<91;)echo chr($i).chr($i+32);

Ungolfed:

0123456789_
<?php 
    for($i=64;++$i<91;) echo chr($i).chr($i+32);

Anything written outside the <?php tag is considered plain text. The for loop in the PHP code echoes the uppercase and lowercase of each letter.

\$\endgroup\$
1
\$\begingroup\$

Brainfuck 36 Bytes (96 commands)

>++++++[-<++++++++>]+++++[<.+.+>-]<+++++++>+++++++++++++[-<.+.+>]<++++.++>+++++++++++++[-<.+.+>]

Explanation:

 >++++++[-<++++++++>]    Increment to '0'
 +++++[<.+.+>-]          Print 10 characters (0 to 9)
 <+++++++>               Increment to lower upper characters
 +++++++++++++[-<.+.+>]  Print 26 characters (A to Z)
 <++++.++>               Increment to '_' Print it and move to a
 +++++++++++++[-<.+.+>]  Print 26 characters (a to z)

EDIT: Most straightforward solution IMHO, still shorter than the others

\$\endgroup\$
1
  • \$\begingroup\$ That's not how we count bytes. In brainfuck, this is a 96-bytes solution, because every command is stored in one byte. You could port it to CompressedFuck though. \$\endgroup\$
    – Dennis
    Commented Jul 20, 2016 at 15:43
1
\$\begingroup\$

Common Lisp, 160 bytes

(setq a 47)(loop(setq a(+ a 1))(princ(code-char a))(when(and(> a 56)(< a 64))(setq a 64))(when(and(> a 89)(< a 96))(setq a 96))(when(> a 121)(return)))(princ'_)
\$\endgroup\$
1
\$\begingroup\$

K, 21 bytes

_ci95,(97+!26),65+!26
\$\endgroup\$
1
\$\begingroup\$

O, 40 bytes

[[D2*(,]B6*(+{n.84*+}dC8*(C4*.9+mr]{nc}d
\$\endgroup\$
1
\$\begingroup\$

C--, 230 bytes

target byteorder little;export main;import putchar,isalnum;foreign"C"main(){bits32 v,t;v = 48;T:t=foreign"C"isalnum(v);if (t!=0){foreign"C"putchar(v);}if (v==95){foreign"C"putchar(v);}v=v+1;if (v<123){goto T;}foreign"C"return(0);}

Ungolfed:

target byteorder little;

export main;
import putchar, isalnum;

foreign "C" main(){
    bits32 v, tmp;
    v = 48;
Top:
    tmp = foreign "C" isalnum(v);
    if (tmp != 0){
        foreign "C" putchar(v);
    }

    if (v == 95){
        foreign "C" putchar(v);
    }

    v=v+1;
    if (v < 123) { goto Top; }

    foreign "C" return (0);
}
\$\endgroup\$
1
\$\begingroup\$

Python 2.x, 63 bytes

print''.join(chr(a)for a in range(123)if chr(a).isalnum())+'_'

Try it online.

Explanation:

chr(a)for a in range(123)if chr(a).isalnum() # generates a list iterating through ascii 
                                             #  symbols, picking just numbers alphabet characters

''.join(...)+'_'                             # joins a list of items with no spacing;
                                             # appends '_' at the end

My first golfing attempt; thanks to mbomb007 for the hints

\$\endgroup\$
3
  • \$\begingroup\$ You can remove some spaces. \$\endgroup\$
    – mbomb007
    Commented Jul 19, 2016 at 15:51
  • \$\begingroup\$ where for example? I thought I got rid of each one I could \$\endgroup\$
    – harry
    Commented Jul 19, 2016 at 17:58
  • \$\begingroup\$ print''.join(chr(a)for a in range(48,123)if chr(a).isalnum())+'_'. Quotes and parentheses/brackets are delimiters. You don't have any, but you can also do something like print 1if 1else 0. See the Tips for golfing in Python page. \$\endgroup\$
    – mbomb007
    Commented Jul 19, 2016 at 19:03
1
\$\begingroup\$

Groovy, 36 characters

print(("0".."z").grep(~/\w/).join())

Sample run:

bash-4.3$ groovy -e 'print(("0".."z").grep(~/\w/).join())'
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
\$\endgroup\$
1
\$\begingroup\$

Julia, 35 bytes

()->join(['a':'z','A':'Z',0:9,'_'])

Alternative solution, also 35 bytes:

()->replace(join('0':'z'),r"\W","")
\$\endgroup\$
0
1
\$\begingroup\$

16-bit x86 machine code, 26 bytes

In hex:

B030B90A00AA40E2FCB05FAA40B11A5040AAE2FC5834207BF4C3

Input: DI: pointer to an array of at least 63 bytes. Function outputs the sequence

0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

without any termination, since its length is constant.

Disassembly:

00: B0 30       mov    al,'0'
02: B9 0A 00    mov    cx,10
_00000005:
05: AA          stosb              ;*DI++=AL
06: 40          inc    ax          ;AL++
07: E2 FC       loop   _00000005   ;Print digits
09: B0 5F       mov    al,'_'      ;0x5f
0B: AA          stosb
0C: 40          inc    ax          ;AX=0x60
_0000000D:
0D: B1 1A       mov    cl,26
0F: 50          push   ax
_00000010:
10: 40          inc    ax
11: AA          stosb
12: E2 FC       loop   _00000010   ;Print single-case letters
14: 58          pop    ax
15: 34 20       xor    al,020      ;Flip "case" bit
17: 7B F4       jnp    _0000000D   ;Repeat if "not parity", i.e. AX is back to 0x40
19: C3          ret
\$\endgroup\$
1
\$\begingroup\$

SML, 70 (lame) bytes, 80 78 71 64 bytes

I did it! The lame solution has been defeated by 6 bytes:

fun&123="_"| &91= &97| &58= &65| &n=str(chr n)^ &(n+1);print(&48)

Try it online! Better readable:

fun t 123 = "_"
  | t 91  = t 97
  | t 58  = t 65
  | t n   = str(chr(n)) ^ t (n+1);
print(t 48)

Keep reading to see past me whining about not having found this solution yet.


print"_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

The sad truth so far: I didn't manage to get something shorter than this, and believe me, I've tried.

Straight forward using build-in functions:

print("_"^implode(List.filter Char.isAlphaNum(List.tabulate(123,chr))))

Generate Char list, filter, implode (char list -> string), add _, print:

_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Uses 71 bytes and is thereby 2 bytes to long to beat the lame solution. As more or less only keywords remain, I'm pretty sure this approach can't be golfed any further.

Let's build our own function!
This approach yielded multiple solutions of which the shortest one

fun&26a=""| &n a=str(chr(n+a))^ &(n+1)a;print(&16 32^ &0 65^ &0 97^"_")

also still needs 71 bytes. At least some a bit more interesting stuff is happening here. Let's name the function f instead of & and have closer look:

1  fun f 26 a = ""
2    | f  n a = str(chr(n+a)) ^ f (n+1) a
3  ;
4  print(f 16 32 ^ f 0 65 ^ f 0 97 ^ "_")
  • 4 f n a returns a string of 26-n consecutive ascii-chars starting at char number a. ^ concats two strings.
  • 1 Pattern matching. If the second argument is 26, return an empty string.
  • 2 Recursion: If n is not yet 26, get the current char, convert it into a string and append it to the (recursively build) rest of the string.
  • 3 Tell the interpreter that we are finished with declaring f so we can use it afterwards.

26-n? Why not do something more intuitive like

fun f 0 a = ""
  | f n a = str(chr(n+a)) ^ f (n-1) a;
print(f 10 47 ^ f 26 64 ^ f 26 96 ^ "_")

, would nobody ask here ever.

Because on the one hand this would print

9876543210ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba_

which albeit correct doesn't look very nice. However, more importantly in this case we have one 0 and two 26 and in the other case two 0 and one 26, which saves 1 byte.

Nevertheless it's still two bytes to go to underbid the infamous solution. At least for this approach remains a tiny bit of hope to achieve this goal, some time, in a brighter future ...
But probably not.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ There's no lowercase z. Typo? \$\endgroup\$
    – owacoder
    Commented Jul 18, 2016 at 18:05
  • 1
    \$\begingroup\$ @owacoder Thanks! That was a typical off-by-one error, as z is char number 122, but List.tabulate has to count to 123 to reach it. \$\endgroup\$
    – Laikoni
    Commented Jul 18, 2016 at 18:10
1
\$\begingroup\$

C, 56 55 bytes

i;k(){for(;putchar(i%26+"aA0"[i++/26])^57;);puts("_");}

Output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_
\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 52 bytes

FOR I=65TO 90?CHR$(I);CHR$(I+32);
NEXT?1234567890;"_
\$\endgroup\$
1
\$\begingroup\$

Tcl, 68 bytes

puts abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

Try it online!


tcl, 99

time {append s [incr i]} 9
set i 64;time {set s $s[format %c%c [incr i] [expr $i+32]]} 26
puts _0$s

demo


tcl, 100

time {append s [incr i]} 9
time {set s $s[format %c%c [expr [incr i]+55] [expr $i+87]]} 26
puts _0$s

demo

\$\endgroup\$
1
\$\begingroup\$

T-SQL, 70 bytes

PRINT'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'

Procedural solutions in SQL are just too long, due to the length of keywords. A couple of my best attempts:

76 Bytes, store the alphabet then UPPER it:

DECLARE @ CHAR(26)='abcdefghijklmnopqrstuvwxyz'PRINT'0123456789_'+@+UPPER(@)

100 Bytes, add all chars from 65-122, then strip out the ones I don't want:

DECLARE @ VARCHAR(99)='0123456789'A:SET @+=CHAR(LEN(@)+55)IF LEN(@)<68GOTO A
PRINT STUFF(@,37,6,'_')
\$\endgroup\$
1
\$\begingroup\$

MATLAB, 30 bytes

['a':'z','A':'Z','0':'9','_']

Very simple :)

Or, at the same cost:

char(48+[49:74,17:42,0:9,47])

or

char([97:122,65:90,48:57,95])
\$\endgroup\$
1
\$\begingroup\$

Japt, 13 12 bytes

;C+B+9ô ¬+'_

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Keg, 15B(The Keg SBCS is in Keg wiki.)

\_\0\9ɧZAɧzaɧ(,

Explanation:

\_#             Push _
  \0\9ɧ#        Push range 0-9
       ZAɧ#     Push range Z-A
          zaɧ#  Push range z-a
             (,#Output

TIO

\$\endgroup\$
1
\$\begingroup\$

x86_16 machine code - 57 bytes

B4 0E         MOV AH, 0EH
        LOWERCASE:
B0 61         MOV AL, "a"
8A D8         MOV BL, AL
CD 10         INT 10H
           LOOP1:
FE C0         INC AL
CD 10         INT 10H
3C 7A         CMP AL, "z"
74 02         JE UPPERCASE
75 F6         JNE LOOP1
        UPPERCASE:
8A C3         MOV AL, BL
24 DF         AND AL, 0DFH
CD 10         INT 10H
           LOOP2:
FE C0         INC AL
CD 10         INT 10H
3C 5A         CMP AL, "Z"
74 02         JE NUMBER
75 F6         JNE LOOP2
          NUMBER:
B0 30         MOV AL, "0"
CD 10         INT 10H
           LOOP3:
FE C0         INC AL
CD 10         INT 10H
3C 39         CMP AL, "9"
74 02         JE UNDERSCORE
75 F6         JNE LOOP3
       UNDERSCORE:
B0 5F         MOV AL, "_"
CD 10         INT 10H
            EXIT:
B8 4C00       MOV AX, 4C00h
CD 21         INT 21H

Running with DOSBox :

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Stax, 7 bytes

ë½óG╨}S

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 51 bytes

f=n=>n>>8?'':(/\w/.test(c=Buffer([n]))?c:'')+f(-~n)

Try it online!

Trivial one

\$\endgroup\$
1
\$\begingroup\$

Noether, 35 bytes

65~a26(a`+BPa`32++BP!`)10(zP!z)95BP

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 41 bytes

"Aa0_""   \0"[ dupd + [a,b] write ] 2each

Attempt This Online!

\$\endgroup\$
3
  • \$\begingroup\$ I don't know how this lang works, but shouldn't you mention the USING: kernel math.ranges math io sequences ; header somewhere? not necessarily as part of your bytecount, but it doesn't seem like a default, correct me if im wrong \$\endgroup\$ Commented Jun 5, 2022 at 22:49
  • 1
    \$\begingroup\$ @thejonymyster Factor is a whole can of worms when it comes to imports. Factor's byte counting policy for imports was painstakingly developed by @Bubbler and others as a balancing act of various factors. Long story short: EVERYTHING has to be imported in Factor. I would have to USE: math if I want to add two numbers. No one wants to see that in every answer. Factor is image-based, so I can have any vocabs I want loaded without explicitly loading them. \$\endgroup\$
    – chunes
    Commented Jun 6, 2022 at 0:27
  • 1
    \$\begingroup\$ The rule is - vocabularies must be mentioned before the byte count unless they are auto-use vocabularies, which most are. \$\endgroup\$
    – chunes
    Commented Jun 6, 2022 at 0:40
1
\$\begingroup\$

Regenerate -as "", 12 bytes

[0-9A-Z_a-z]

Attempt This Online!

If Regenerate supported character class shortcuts, then \w would work as a 2-byte solution.

\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 27 bytes

'_',⎕UCS∊47 64 96+⍳¨10,2⍴26
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice answer! I suggest you add a short explanation to help people understand how the code works. \$\endgroup\$
    – Seggan
    Commented Jul 11, 2022 at 16:22
0
\$\begingroup\$

R

cat(letters,LETTERS,0:9,"_",sep="")

I believe this does not count as letters and LETTERS are built-in constants. But this one should be fine:

cat(intToUtf8(c(65:90,97:122)),0:9,"_",sep="")
\$\endgroup\$
0
\$\begingroup\$

Actually, 24 bytes

"[\]^`""A{"Oix♂c-9ur♂$+Σ

Try it online!

There's probably a shorter way

Explanation:

"[\]^`""A{"Oix♂c-9ur♂$+Σ
       "A{"O              push a list containing the ordinals of "A" and "{"
            ix            flatten the list, end-exclusive range
              ♂c          convert each ordinal into its corresponding character
"[\]^`"         -         remove non-alphabetic characters except "_"
                 9ur♂$+   push range(10), convert to strings, concatenate lists
                       Σ  concatenate strings in the list
\$\endgroup\$
0
\$\begingroup\$

Perl 6

put |grep /<alnum>/,'0'..'z'
put |grep /\w/,'0'..'z'

Explanation:

put # 「print()」 but with trailing newline

# turn the following into a Slip so that there aren't 
# any spaces in the output
|

grep
  /\w/,      # match wordchars
  '0' .. 'z' # in this Range

( grep returns a List, which puts spaces between each element when stringified )

\$\endgroup\$
0
\$\begingroup\$

Erlang, 56 bytes

f()->[X||X<-lists:seq(1,$z),re:run([X],"\\w")/=nomatch].


Erlang, 57 bytes

f()->S=fun lists:seq/2,[$_|S($0,$9)]++S($A,$Z)++S($a,$z).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.