43
\$\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
    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
    Feb 24, 2021 at 3:43
  • \$\begingroup\$ Is duplication of one char allowed? \$\endgroup\$
    – l4m2
    Feb 24 at 17:42
  • \$\begingroup\$ @l4m2 No. "To be precise, the following characters need to be output, and no more." \$\endgroup\$
    – orlp
    Feb 25 at 15:49
  • \$\begingroup\$ and no more can be parsed as "No more kind of chars" \$\endgroup\$
    – l4m2
    Feb 25 at 15:51

101 Answers 101

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\$

K, 28 bytes

_ci,/(97 65+\:!26),95,48+!10

Generates [97..122]++[65..90]++[95]++[48..57] and maps the numbers to chars.

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

SMBF, 29 bytes

<[<.-<.->>-]<<-.<[<.->-]9
zZ

Try it online

The last byte is a literal \x1A (decimal 26). It shows in the "edit" mode of this answer as a tiny arrow, but cannot otherwise be seen for some reason...

I use literals in the source code to provide a starting value and how many times to loop. 26 times for the loop printing Z-A and z-a, then subtract and print _, then use the newline (decimal 10) to print 9 and subtract, looping 10 times.

Output:

ZzYyXxWwVvUuTtSsRrQqPpOoNnMmLlKkJjIiHhGgFfEeDdCcBbAa_9876543210
\$\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\$

ZX Spectrum, (Machine Code) 27 bytes

start in BASIC with PRINT "" AND USR 4e4

      org 40000
      dump 40000


      ld b,"z"
      ld a,"_"
      rst 16
nchar ld a,b
      cp "/"
      ret z
      cp ":"
      jr c,ok ; print numbers
      sub "A"
      cp "Z"+1-“A”
      ld a,b ; undo change
      jr c,ok ; print A-Z
      cp "a"
      jr c,fnext ; in between ranges
ok    rst 16
fnext djnz nchar

Hexcode

067A3E5FD778D641fe1a78380b
413809FE5B3804FE613801D710Ea

Output: _zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210

\$\endgroup\$
2
  • \$\begingroup\$ Can we have a hexdump of the compiled version? \$\endgroup\$ Jul 19, 2016 at 17:37
  • \$\begingroup\$ Will make it later. \$\endgroup\$ Jul 19, 2016 at 21:02
1
\$\begingroup\$

Lua, 64 bytes

s="abcdefghijklmnopqrstuvwxyz"print(s..s:upper().."_0123456789")

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ I tried your code with this and it doesn't print numbers. \$\endgroup\$
    – user65167
    Feb 10, 2017 at 19:53
  • \$\begingroup\$ @PrzemysławP Just ran it in the demo environment and it ran just fine (printing out abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_) \$\endgroup\$
    – Katenkyo
    Feb 14, 2017 at 15:23
  • \$\begingroup\$ Yes, but question was to output also 0123456789, right? \$\endgroup\$
    – user65167
    Feb 14, 2017 at 15:42
  • 1
    \$\begingroup\$ @PrzemysławP Wow, how did I missed that ?! Thanks, it's fixed now, it should be printing abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789 \$\endgroup\$
    – Katenkyo
    Feb 14, 2017 at 16:05
1
\$\begingroup\$

Zsh, 27 bytes

ls>{0..z}|tr -dc 0-9A-Za-z_

Attempt This Online!

Explanation:

  • >{0..z}: create files named 0 1 ... (all the ASCII characters in between) ... y z
  • ls: list all those newly created files
  • tr -dc 0-9A-Za-z_: remove all characters except 0-9A-Za-z_

ls> works on arrays (unlike <<<), but is shorter than echo. (doesn't work if you care about order or duplicates). There's your newly discovered golfing tip of the day!

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

Excel, 54 48 bytes

-6 bytes thanks to @TaylorRaine

=CONCAT(ROW(1:10)-1,CHAR({64,96}+ROW(1:26)))&"_"

Original Answer

=CONCAT(ROW(1:10)-1,CHAR(ROW(2:3)*32+COLUMN(A:Z)))&"_"

Link to Spreadsheet

\$\endgroup\$
2
  • 2
    \$\begingroup\$ If you replace the innards of the Char statement with {64,96}+ROW(1:26), you can get this down to 48 bytes \$\endgroup\$ Feb 25 at 1:25
  • 1
    \$\begingroup\$ Thanks. That's what happens when you get locked in on a way to do something. \$\endgroup\$
    – Axuary
    Feb 25 at 13:11
1
\$\begingroup\$

Java (JDK), 71, 70 bytes

(b,B)->{B="_";for(b=47;b++<122;)B+=b>57&b<65|b>90&b<97?"":b;return B;}

Try it online!

Inspired by an answer from dorukayhan this is a java.util.function.BiFunction<Character, String, String>

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

Pip, 9 7 bytes

C,E7~XW

Attempt This Online!

Explanation

C,E7~XW
  E7     2 to the 7th power (128)
 ,       Range
C        Cast each integer in the range to a character
    ~XW  In each character, find the first regex match of `\w`

The result is a list of values, some of which are nil, some of which are an alphanumeric or underscore character. By default, Pip outputs lists with no separator, and nil outputs nothing; so the output of the program is simply the requested characters plus a trailing newline.

\$\endgroup\$
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\$
0
\$\begingroup\$

Excel VBA, 130 bytes

Have fun hitting enter...

Sub q()
For i = 1 To 123
If i > 47 And i < 58 Or i > 64 And i < 91 Or i > 96 And i < 123 Or i = 95 Then MsgBox Chr(i)
Next
End Sub
\$\endgroup\$
0
\$\begingroup\$

brainfuck, 105

first code golf attempt using this

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

ungolfed

>++++++[<++++++++>-]         // p1=48
++++++++++                   // p2=10
[-<.+>]<                     // print 0-9, p1=58, p2=0
+++++++                      // p1=65
>>+++++[<+++++>-]<+          // p2=26
[-<.+>]<                     // print A-Z, p1=91, p2=0
++++.++                      // print underscore, p1=97 
>>+++++[<+++++>-]<+          // p2=26
[-<.+>]                      // print a-z
\$\endgroup\$
2
  • \$\begingroup\$ ++++++++++++++++++++++++++++++++++++++++++++++++ That can be done better. \$\endgroup\$
    – orlp
    Jul 18, 2016 at 20:30
  • \$\begingroup\$ improved the +x26 as well \$\endgroup\$
    – Kevin L
    Jul 19, 2016 at 13:23
0
\$\begingroup\$

Javascript (Using external library) (105 bytes)

_.Range(97,26).Concat(_.Range(65,26).Concat(_.Range(48,10))).Push(95).Write("",x=>String.fromCharCode(x))

What this does is gets the char code ranges from a-z, concats with A-Z, then concats 0-9, then pushes the code for _. Write takes a delimiter and joins everything together

Library: https://github.com/mvegh1/Enumerable/blob/master/linq.js

enter image description here

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

PHP, 74 71 bytes

echo 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
\$\endgroup\$
0
\$\begingroup\$

Brainfuck - 116 commands

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

Output: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz

How it works

>++++++++[<++++++>-] Get yourself up to \48, the start of [0-9]

>+++[<+++>-]<+ Count up 10

[<.+>-] Then print each character and bump it up

++[<+++>-]<+> jump up to the start of [A-Z]

>++++[<++++++>-]<++ start a counter of 26

[<.+>-] and print and increment 26 values

<++++.++> jump to [a-z], stopping in at _

>++++[<++++++>-]<++ counter of 26

[<.+>-] and print and increment 26 values

there's got to be a way to simplify that counter to 26 and the print happening twice, but I'm not nearly good enough with brainfuck to do so

\$\endgroup\$
1
  • \$\begingroup\$ 48 doubled is 96, so you could use replace the initial loop with >++++[>++++++[>++>++++<<-]<-] to get both. Probably shorter than two output loops. \$\endgroup\$
    – primo
    Jul 20, 2016 at 9:23
0
\$\begingroup\$

dc, 50 bytes

[la1+ddsaPlc>b]dddsb96saC2scx64sa90scx47sa57scx95P

This doesn't feel very elegant.

[              # Open macro definition
 la 1+         #  Load a, increment
 dd            #  Duplicate a+1 twice
 sa            #  Store a+1 as `a'
 P             #  Print new value of a as a character
 lc>b          #  If c>a, do this again
]              # Close macro definition
ddd sb         # DDDuplicate and store as `b'
96sa C2sc x    # Set lower and upper bounds (`a' and `c') for [a-z] and execute a copy of b
64sa 90sc x    # Set bounds for [A-Z] and execute a copy of b
47sa 57sc x    # Set bounds for [0-9] and execute a copy of b
95P            # Print underscore
\$\endgroup\$
0
\$\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\$
0
\$\begingroup\$

RETURN, 20 bytes

'_0 9
'a'z
'A'Z
,,,,

Try it here.

Creates a series of charcode ranges and outputs them.

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

𝔼𝕊𝕄𝕚𝕟, 10 chars / 13 bytes

Ⓒ…⩥ṻ)ŋ/\W⌿

Try it here (ES6 browsers only).

Translated roughly to ES6:

String.fromCharCode(_.range(123)).replace(/\W/g,'')
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 61 bytes

using formule for lowercase'ing from Practical Lisp, namely (format t "~(~a~)" "ExAMpleStRINg")

(format t"~a~:*~(~a~)0123456789_"'abcdefghijklmnopqrstuvwxyz)

Ideas for improvement are welcomed.

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

QBIC, 66 41 bytes

Had some coffee and re-read the specs:

[65,90|?chr$(a)+chr$(a+32)]?@0123456789_`

This prints Aa\n all the way up to Zz\n, then the literal 0123456789_.


There are quite a lot of ways QBIC can approach this challenge if we want to print the string in the order provided.

By adding all the requested ranges to Z$ (Z$ gets printed implicitly), 71 bytes

[97,122|Z=Z+chr$(a)][65,90|Z=Z+chr$(b)][48,57|Z=Z+chr$(c)]Z=Z+chr$(95)

Printing each range to screen, with ';` to prevent newlines, 67 bytes

[97,122|?chr$(a)';`][65,90|?chr$(b)';`][48,57|?chr$(c)';`]?chr$(95)    

Creates one range, printing only substrings, 70 bytes

[48,122|A=A+chr$(a)]?mid$(A,50,26)+mid$(A,18,26)+left$(A,10)+chr$(95)

Creating one range, but with modified start of that range, 69 bytes

[122|A=A+chr$(a)]?mid$(A,96,26)+mid$(A,64,26)+mid$(A,47,10)+chr$(95)

But sadly the best at 66 bytes, just plainly printing this string:

?@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_`
\$\endgroup\$
0
\$\begingroup\$

q/kdb+, 35 bytes

Solution:

("c"$48+(!)75)except":;<=>?@[\\]^`"

Example:

q)("c"$48+(!)75)except":;<=>?@[\\]^`"
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"

Notes:

Turns out I cannot read :) Q.an solves this in 5 bytes. I'll try to golf this new solution.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ "Built-ins that contain 9 or more of these characters are disallowed." \$\endgroup\$ Jun 22, 2017 at 23:34
0
\$\begingroup\$

RProgN 2, 9 bytes

•zR.'\W'-

Explained

•zR.'\W'-
•           # Push a space
 z          # Push the character 'z'
  R         # Create a stack of all characters from space to z.
   .        # Concatenate them into a single string.
    '\W'-   # Filter out everything that matches the regex '\W' (Non-alpha-numeric characters)
            # Implicit print

Try it online!

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

JavaScript (ES7), 60 57 bytes

Shame we can't return an array or set of the characters, I could've saved quite a few bytes there.

_=>[...new Set(Object.keys(this).join`4Z_`+2**29)].join``

Test it

The second line is sorted to make it easy to check all characters are included.

f=
_=>[...new Set(Object.keys(this).join`4Z_`+2**29)].join``
o.innerText=f()+`\n`+[...f()].sort().join``
<pre id=o></pre>

\$\endgroup\$
1
  • \$\begingroup\$ G J K N Q U missing on Firefox 97.0 \$\endgroup\$
    – l4m2
    Feb 24 at 17:47
0
\$\begingroup\$

Fortran 95, 131 bytes

write(*,1)(char(i),i=97,122)
write(*,1)(char(i),i=65,90)
write(*,2)(i,i=0,9)
write(*,1)'_'
1 format(1A,25A,$)
2 format(10I1,$)
end

Just because every challenge is improved by a Fortran entry.

You'd think it would be easy to golf this down, but the required variable declarations get expensive very quickly so I think this is about as short as it's going to get.

If delimiters (\n) were allowed between characters in the output, this could be reduced to 83 bytes:

print*,(char(i),i=97,122)
print*,(char(i),i=65,90)
print*,(i,i=0,9)
print*,'_'
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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