Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Your task is to build a program (using only printable ASCII characters and/or tabs and newlines) that prints out exactly the characters in the printable ASCII space (0x20 to 0x7e) that don't appear in your program's source code (in any order, however many times you want).

The shortest code to do this in any language wins.

share|improve this question
    
tabs and newlines are printable ASCII characters. –  Bakuriu Aug 23 '13 at 18:49
7  
They are, but they're not in the range 0x20 to 0x7e, which are defined as the "printable ASCII characters". Technically tabs and newlines are actually control characters. –  Joe Z. Aug 23 '13 at 19:22
2  
Are we allowed to print newlines (or any other unprintable ASCII characters)? –  flornquake Aug 24 '13 at 0:30
4  
I just created an account to upvote this post. –  user8953 Aug 24 '13 at 4:47
2  
Yaaay, this is ranked third in the Stack Exchange "hot questions" list! We're getting more attention :D –  Doorknob Aug 24 '13 at 17:15

51 Answers 51

up vote 85 down vote accepted

PHP 5.2, 4

<?<<

Save as a file called NYUIOMK()'DEAQRWVX[Z]\^@CBGFJqwv{z}|~`bgfkj203547698;=>!#"%$&+*-.php somewhere in /home. short_open_tag needs to be On in your php.ini.

The output is:

PHP Parse error:  syntax error, unexpected T_SL in /home/wherever/NYUIOMK()'DEAQRWVX[Z]\^@CBGFJqwv{z}|~`bgfkj203547698;=>!#"%$&+*-.php on line 1
share|improve this answer
25  
Haha, nice bending of the rules. –  Johannes Kuhn Aug 27 '13 at 19:12
4  
Nice, but unfortunately I can spot a : in the output. –  Howard Aug 28 '13 at 4:57
2  
@AJMansfield: I know… same to Cruncher. Don’t think it matters. –  minitech Nov 28 '13 at 22:27
2  
15  
I appreciate it, @TheGuywithTheHat, but I answered this about a year ago, as opposed to yesterday. –  minitech Feb 27 at 18:07

Polyglot, 95

Works in

  • Tcl
  • Perl
  • Bash
  • Brainfuck
  • Ruby
  • Coffescript
  • C - if no main() is needed. Thanks to ugoren
  • Golfscript
  • Python
  • R
  • Julia
  • Probably more.
#undef X;A!"$%&'()*+-[,.]/0123456789:<=>?@BCDEFGHIJKLMNOPQRSTUVWYZ\^_`abcghijklmopqrstvwxyz{|}~

Does nothing.

share|improve this answer
7  
No, but this is a polygot. I don't want to destroy that. –  Johannes Kuhn Aug 23 '13 at 16:26
33  
I fed this into the GNU Fortran compiler and it segfaulted. –  marinus Aug 23 '13 at 16:43
7  
In C, #undef X;whatever junk you want works. –  ugoren Aug 23 '13 at 16:56
5  
Works in Python too (because it uses # for comments like Ruby and Perl) –  Doorknob Aug 23 '13 at 17:15
29  
"The shortest code to do this in any language wins." For the lack of a code that works in any language, this entry should win, since it's the code that works in the greatest number of languages. ;-D –  msb Aug 27 '13 at 23:33

GolfScript, 15 12 characters

{`),32>^.}.~

Based on Jan Dvorak's answer with a few twists and also in the style of Peter Taylor's one.

share|improve this answer

Whitespace, 61 57 characters

It's not the shortest but it probably has the simplest logic (it's just a loop really).

Here it is completely commented, where S is space, T is tab, L is line feed:

SSSTSSSSSL     # push 0x20
LSSSL          # label S
SSSTL          # push 1
TSSS           # add
SLS            # duplicate top of stack
SLS            # duplicate again
TLSS           # output ASCII character
SSSTTTTTTSL    # push 0x7E
TSST           # subtract (result - 0x7E)
LTTSL          # branch to label S if top of stack is negative
LLL            # end

Thanks to @r.e.s. for correction to the above (required extra duplicate for the branch instruction) and for smaller numbers to push on the stack.

share|improve this answer
1  
This doesn't work as-is, but can be fixed by inserting a duplicate-top-of-stack (SLS) immediately before the conditional branch (LTTSL) -- it's needed because the conditional branch command removes the top-of-stack. The resulting 64-character program works as advertised. (If the program is stored in a file with .ws extension, it can be tested online at golf.shinh.org/checker.html) –  r.e.s. Aug 25 '13 at 16:24
    
Also, the program length can be reduced to 57 using nearly the same program but with the three pushed numbers -94, 127, 126 changed to 32, 1, 126, respectively: SSSTSSSSSL LSSSL SSSTL TSSS SLS SLS TLSS SSSTTTTTTSL TSST LTTSL LLL. –  r.e.s. Aug 25 '13 at 19:39

Golfscript, 26 24 characters

"126,32>''+".~\-'.~\-"'-

Takes a range generation script, duplicates it, executes it, substracts it from its result, then substracts the result subtraction code and the other quote character.

share|improve this answer
2  
Damn, that's clever. –  marinus Aug 23 '13 at 17:28
1  
Remove ''+, escape program before subtraction, put in a noop .; (didn't find a better way to cover the dot), use code block instead of string -> {126,33>`-.;}.~ which is 16 chars –  Howard Aug 23 '13 at 18:17
    
And utilising in any order, however many times you want you can also remove the semicolon. –  Howard Aug 23 '13 at 18:52
    
@Howard I'm afraid I don't understand your idea. You can post it as a separate answer. –  Jan Dvorak Aug 23 '13 at 18:53
    
@PeterTaylor I thought I printed a space? –  Jan Dvorak Aug 23 '13 at 19:05

Ruby, 81 78 68 66 62 57

(?!..?~).map{|a|$><<a if/[()ifmap{}|?!.~\/\\\[\]$><]/!~a}

Simply checks itself. Duplicate characters manually removed.

Thanks to Josh for saving 4 characters, and minitech for saving 5 characters!

share|improve this answer
    
Can't you put the if after the $><<x to save one of the end lines? –  Josh Aug 23 '13 at 23:10
    
@Josh Yes. I will do that now. –  Doorknob Aug 23 '13 at 23:26
    
You can take it to 58: (?!..?~).map{|x|$><<x if/[()ifmap{}|x?!.~\/\\\[\]$><]/!~x} –  minitech Aug 25 '13 at 15:15
1  
Ah, and with a better choice of variable name, 57: (?!..?~).map{|a|$><<a if/[()ifmap{}|?!.~\/\\\[\]$><]/!~a} –  minitech Aug 25 '13 at 15:18

C, 83 74 69 characters

main(z) {for(;++z<96;"\33iE!vk?}GkRP8z"[z/7]&1<<z%7&&putchar(z+32));}

I really tried to get it down below 80 characters, but I just haven't been able to pull it off. I finally decided to post what I have, on the assumption that I (or someone else) will figure out 79-character solution ten minutes after posting this. Okay, it wasn't quite ten minutes, but it worked in principle.

I really wanted to post a version that didn't have to have a gratuitous space in the source code, but that one landed in a strange-attractor orbit, bouncing between a handful of solutions. After many minutes of trying to nudge one of them into a stable solution, I gave up and added the space.

share|improve this answer

I know it's not winning any contests. I just wanted to try it in a language not normally used, just for kicks.

Java - 209 195 152 140 characters

class a{public static void main(String[]a){for(char c=0;;c++)System.out.print("publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:}".indexOf(c)<0?c:"");}}

With line breaks and tabs

class a{
    public static void main(String[]a) {
        for(char c=0;;c++)
            System.out.print("publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:} ".indexOf(c)<0?c:"");
    }
}

Beware if you execute: program does not terminate. Haha

Explanation

  1. for(char c=0;;c++): Since a char can be treated as an int, I use that to my advantage here to increment through all possible values of c. I omit the terminating condition in the loop (the one that would go between the two semicolons) in order to save on characters, since it wasn't specified that the program had to terminate. :)
  2. "publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:} ".indexOf(c)<0?c:"": Sadly, not a very elegant approach, but it gets the job done. Manually list every character present in the source code as a String literal, then check whether the current char c occurs within it with indexOf(). If the indexOf() call returns -1, it doesn't exist, and therefore we should print it. The rest of it just uses the ternary operator to save on characters and space.
share|improve this answer
    
can you explain a bit? –  joey rohan Oct 1 '13 at 18:01
1  
@joeyrohan Sure, just added an explanation below it. :) –  Jeff Gohlke Oct 1 '13 at 18:10
    
cool ;) nice stuff :) –  joey rohan Oct 1 '13 at 18:12
1  
You could put the ENTIRE ascii printable table in a comment and make a java programm that returns nothing. It'd beat yours :-) –  Arlaud Pierre Nov 28 '13 at 13:29
    
I gave an answer with 124 characters ;p –  Arlaud Pierre Nov 28 '13 at 13:45

Perl, 49 characters

say grep/[^+-246\[-^aceghmprsy]/,map chr,041..126

This is an interesting challenge -- it's sort of the anti-quine, and I've managed to shorten the program a couple of times by increasing the range of characters that appear in it.

share|improve this answer

Your task is to build a program (using only printable ASCII characters and/or tabs and newlines)

Gosh, you made it hard for APL (Is that delibarate?)
So I decide to Ignore All Rules!!!

APL(Dyalog), 3 10

⎕AV

Prints the atomic vector (which includes all prinable ASCII characters)


Turns out I completely forgot about the "without" part...
But that's an easy fix

⎕AV~'AV'''

~'AV''' means exclude (~) the characters A, V and single quote (escaped as doubled single quotes)

Regarding printing non-ASCII, well, I am Ignoring All Rules.

share|improve this answer
    
"print[s] out exactly the characters in the printable ASCII space (0x20 to 0x7e) that don't appear in your program's source code" I believe the output may not contain characters outside of the printable ASCII space ("exactly" being the keyword), and your program contains 'A' and 'V' so they should not be printed. –  FireFly Oct 4 '13 at 18:11
    
You'll at least want to add ~ to the set of excluded characters. ;-) Btw, a similar J solution would be a.-.'a.-''' –  FireFly Oct 4 '13 at 19:14
    
You can Ignore All Rules, but that does disqualify you from being the accepted answer. –  Joe Z. Oct 12 '13 at 2:35

JavaScript - 88

alert("BCDFGHIJKMNPQUVXYZ".toLowerCase())// !#$%&'*+,-0123456789:;<=>?@[\]^_`{|}~AERTOWS

prints "bcdfghijkmnpquvxyz"

share|improve this answer
    
Wow I like the toLowerCase idea, it's brilliant! –  Arlaud Pierre Nov 29 '13 at 15:20
1  
Feel free to upvote my answer if you liked it ;) –  xem Nov 29 '13 at 15:45
    
+1 I like it too, xom –  Tim Seguine Jan 30 at 11:56
    
This bad-name-spelling joke is sooo last month dude ;) –  xem Jan 30 at 16:22

GolfScript (18 16 chars)

"),@`^^32>#.~".~

Online demo with an extra line which does a correctness check and outputs the number of characters in error.

(I have various equivalent alternatives. @`^ can be replaced with \\`; # can be replaced with ` or ]. The right combination can be used with Howard's trick to equal his score of 15 because backslashes don't need escaping in blocks the way they do in string literals: {),\`^32>].~}.~. But Howard deserves the credit for that trick).

share|improve this answer
1  
nice rule abuse :-) golfscript.apphb.com/?c=ImAnficoLCszMj5cXC0uIi5%2B –  Jan Dvorak Aug 23 '13 at 19:09
2  
Fortunately ascii ends in }~ - even better for code blocks, see my new answer ;-) –  Howard Aug 23 '13 at 20:22

Fish - 80

zbcdjkpqruvwxaABCDEFGHIJKLMNOPQRSTUVWXYZ#!"'$%^&*()@!+-[]{},;:/\<>=?|~0123456789

When fish errors it prints out "something smells fishy...". Since z is a bad instruction it errors right away

share|improve this answer

J (52 40)

Edit: Duh, forgot about e.

'''(-@.e#[)~95{32}a'(-.@e.#[)~95{.32}.a.

Old version:

(>@(*/@('(>@*/''&~:).#]32{95}a'&~:)&.>)#])95{.32}.a.

Other variant (same length but less output):

([#~*/"1@('([#~*/"1@''&:0)95{.32}a'&~:"0))95{.32}.a.
share|improve this answer
    
@JanDvorak: whoops typo –  marinus Aug 23 '13 at 16:34
    
Darn it! I was hoping I could get low enough in Ruby to beat you and then you drop it all the way to 40. :P –  Doorknob Aug 23 '13 at 17:08
    
The new one looks much more quiney. –  Jan Dvorak Aug 23 '13 at 17:10
1  
@Doorknob: I have one in APL that's only 24 characters but it has non-ASCII characters in it. –  marinus Aug 23 '13 at 17:11
    
Yeah, I did the ASCII thing to avoid languages like APL. –  Joe Z. Aug 23 '13 at 19:38

Befunge (48)

<|::-1,+*88:<+3*87
6<@.**85
9>"()~&"/%$ |!#';=?}

Outputs: {zyxwvutsrqponmlkjihgfedcba`_^][ZYXWVUTSRQPONMLKJIHGFEDCBA240

share|improve this answer
    
Holy cow! Nice work! –  Cruncher Nov 28 '13 at 18:21

Python 3 - 68 61

x=r"print(*set(map(chr,range(32,127)))-set(x+'=\"'))"
exec(x)

... thanks to @WolframH for the improvements.

share|improve this answer
1  
I think you can put exec(x) in a new line and save the ; in x. Also, in Python 3, you can use x=r"print(*set(map(chr,range(32,127)))-set(x+'=\"'))"\nexec(x) for 61 chars (prints multiple spaces, which is allowed). –  WolframH Aug 24 '13 at 22:46
    
@WolframH ingenious, thanks! –  Zero Piraeus Aug 24 '13 at 23:13

Brainfuck, 173

+++++[->++++++<]>>>++[------<+>]<++++>>----[----<+>]>-[-------<+>]>-[---<+>]<------->>-[---<+>]<+++++++++>>--[-----<+>]<+++++>>+[---------<++>]+++++++++++++[<[.+<]>[>]<-]\=,

Pretty long, I might try again later.

share|improve this answer

Javascript, 92

(function f(){for(i=32;126>i++;)!~(""+f).indexOf(c=String.fromCharCode(i))&&console.log(c)})()
share|improve this answer
    
Is this a fair solution? alert(' !"#$%^*+/-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`bcdfghijkmnopqsuvwxy‌​z{|}~') Comes in at 95 chars and is dumb as hell. :p –  tristin Oct 2 '13 at 18:59
2  
@tristin :P yeah javascript is a bit verbose when it comes to charcode to string. And isn't it output every character your program dosn't have. The text your alerting is in your program as well :) –  C5H8NNaO4 Oct 3 '13 at 9:09
1  
Haha, oops. Oh well. –  tristin Oct 3 '13 at 19:09

Not very serious, but I had to give it a go:

JSFuck (138152)

(compiled source here)

Original source:

for(x=0x7e;x>0x19;x--){
    console.log(String.fromCharCode(x).replace(/[\[\]!\+\(\)]/ig, ''))
}

Prints all characters except ()+[]!

share|improve this answer
    
(x) <=> [x][+[]], increases code size but makes the alphabet needed smaller. –  FireFly Oct 3 '13 at 21:18

PHP - 93

<? //A"$%&'()*+[,.]/0123456789:=-@ABCDEFGHIJKLMNOPQRSTUVWYZ\^_`abcdefghijklmopqrstuvwxyz{|}~#

Output:

nothing

The OP asks to print all the unused characters, well, I just use them all

share|improve this answer

sh (47)

tr</dev/urandom -cd \[:print:]|tr -d "`cat $0`"

Uses the self-referential approach. Assumes /dev/urandom will eventually output every octet at least once. Doesn't terminate.

If we assume that man is installed, we could instead make use of the ascii(7) manpage (and thus have a terminating program) (44 chars, thanks @fennec).

man ascii|tr -cd \[:print:]|tr -d "`cat $0`"
share|improve this answer
    
Could you use another file, possibly with a shorter name, that's essentially guaranteed to have all possible octets? and might even terminate? I'm thinking like /dev/memory or something. –  fennec Jan 30 at 14:20
    
@fennec if we assume that man and zsh are installed, man zshall seems to fit the criteria. I could add that as a variation. –  FireFly Jan 30 at 18:20
    
man ascii could save you another letter, I think. –  fennec Jan 31 at 2:51

Python - 68 83,88 (but it actually reads the file)

No comments, no hacks, it just opens itself, and checks the contents. Includes the set logic from @ZeroPiraeus's answer.

print"".join(set(map(chr,range(32,127)))-set(open(__file__).read()))

Changed to print the output and not an array.

share|improve this answer
1  
Outputs the following characters which are in the program: ` 127[]acdefrtx` –  Zero Piraeus Aug 24 '13 at 2:24
    
@ZeroPiraeus I've corrected that, and have met your score! –  Lego Stormtroopr Aug 24 '13 at 5:47
3  
These are definitely not ASCII characters. ASCII below 32 only contains control codes (Backspace, Bell, etc.), whitespace (CR, LF, tab), and the null char. –  Felix Dombek Aug 24 '13 at 13:25
1  
@Felix These are from Code page 437 (which starts at U+2639, I believe) –  Doorknob Aug 24 '13 at 15:02
1  
You can get this down to 62 chars in python3 using @WolframH 's idea: print(*set(map(chr,range(32,127)))-set(open(__file__).read())). Longer by 1 character than the other answer, but more pythonic in my opinion –  Peter Gibson Aug 29 '13 at 1:47

Definitely the longest solution here, but coding in Lino is always fun:

L.in.oleum - 655 523 characters

"libraries"/arch/cpu/base;/hmi/conout;/data/bytes;/data/string/t2s;/data/heap;/data/heap/connect/mgrab;"stockfile"a;"directors"displaystatus=engage;"injection"c=524;b<-bytes.bytesizeconvert:c;b<-heap.alloc:b;a<-heap.alloc:c;[filecommand]=readfile;[filename]=stockfile;[fileposition]=0;[fileblocksize]=c;[fileblockpointer]=b;arch.fileread;[string.psource]=b;[string.ptarget]=a;string.t2s;b<-heap.alloc:7fh;c=32;d=b;"f"[d_32]=c;+c;+d;?c<7fh>f;"w"d=[a];+a;?d=0>y;?d<32>w;?d>7eh>w;e=b;e+d;[e]=33;^w;"y"b+32;"v"conout.say:b;bye;

No comments, just reads the source compiled into binary. Save as a.txt or it won't compile!

share|improve this answer

J - 21

(u:32+i.97)-.1!:1<":5

write this to a file called 5 in the current directory. Then load execute the script with 0!:1<'5'

Or 25 without the file trick:

(-.~".)'(":u:32+i.0-~95)'
share|improve this answer
    
Source code contains ', which isn't removed from the output. –  FireFly Jul 13 at 2:52

Haskell (71)

import Data.List
main=putStrLn$[' '..'~']\\" \\\"$'.=DLS[]aimnoprstu~"

The boring duplicate-characters-in-program-in-a-string, subtract-from-universal-set solution. Far from a codegolf winner, though it's surprisingly legible for its length.

(Now with list subtraction instead of filter/notWith.)

share|improve this answer

Q, 44

-1"c"$til[128]except"i"$"-1\"c$til[28]exp;";

.

q)-1"c"$til[128]except"i"$"-1\"c$til[28]exp;";
345679:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abdfghjkmnoqrsuvwyz{|}
share|improve this answer

PowerShell: 96

Must be saved and run as a script.

diff([char[]](gc $MyInvocation.InvocationName))([char[]](32..126))-Pa|?{$_.SideIndicator-eq'=>'}

diff is a built-in alias for Compare-Object.

gc is a built-in alias for Get-Content.

$MyInvocation.InvocationName gets the full path to the script being executed.

32..126 is the decimal equivalent for 0x20..0x7e, and so creates an array of the decimal ASCII codes we're looking for.

[char[]] takes the contents of the next object and puts them into an array, breaking them up and converting them into ASCII characters. So, we now have two arrays of ASCII characters - one pulled from this script, the other defined by the challenge criteria.

-Pa sets Compare-Object to "Passthru" format, so only the items which are found different between the inputs are output at the console - indicators of which items were in which input are still stored in the object's data, but are not displayed.

|?{$_.SideIndicator-eq'=>'} pipes Compare-Object's output to Where-Object, which filters it down to only the items which are exclusive to the second input.

share|improve this answer

Clojure (142, 106, 103)

(defn -main[](let[c"(fn[l](pr(reduce disj(set(map char(range 32 126)))l)));-\\\"o"]((load-string c)c)))

formatted:

(defn -main []
  (let [c "(fn[l](pr(reduce disj(set(map char(range 32 126)))l)));-\\\"o"]
    ((load-string c) c)))

Think this does it, may need some tweaks. output:

#{@ ` ! A B b # C $ D % E & F ' G H I * J + K k , L M . N / O 0 P Q q R S 4 T 5 U V v 7 W w 8 X x 9 Y y : Z z { < | = } > ^ ? _}

runs the string, which is evaluateable clojure code, on itself. String has some comments at the end to get the characters used outside of the string (main method, etc)

share|improve this answer

Python - 69

for x in range(38):print chr(x+59)#!"$%&'*,-./012467bdjklmqsuvwyz{|}~

I use the longest (that I'm able to find) sequence of continuous chars I can print out and add the others as a comment after the code.

share|improve this answer
5  
I'm not going to upvote anything that has a comment –  Jan Dvorak Aug 23 '13 at 16:46
    
My answer should show the worst possible way to solve this task. (Use the comment loophole). –  Johannes Kuhn Aug 23 '13 at 16:52
5  
ok... except for that polyglot that is nothing but a comment. –  Jan Dvorak Aug 23 '13 at 17:04
    
@JohannesKuhn However, as it's the longest code that works, it won't win the contest. :P –  Joe Z. Aug 23 '13 at 17:11
3  
@JoeZ. it wins by a wide margin if you divide by the number of languages it works in –  Jan Dvorak Aug 23 '13 at 19:09

Ruby (50)

puts (?#..?~).to_a.join.tr"()?!#.,~_aijnoprstu",""

Outputs:

$%&'*+-/0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^`bcdefghklmqvwxyz{|}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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