The Challenge
The shortest program by character count that outputs the n-bit Gray Code. n
will be an arbitrary number smaller than 1000
100000
(due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.
Note: I don't expect the program to print the gray code in a reasonable time (n=100000
is overkill); I do expect it to start printing though.
Example
Input:
4
Expected Output:
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
Mathematica 50 Chars
Thanks to A. Rex for suggestions!
Previous attempts
Here is my attempt in Mathematica (140 characters). I know that it isn't the shortest, but I think it is the easiest to follow if you are familiar with functional programming (though that could be my language bias showing). The addbit function takes an n-bit gray code and returns an n+1 bit gray code using the logic from the wikipedia page.. The make gray code function applies the addbit function in a nested manner to a 1 bit gray code, {{0}, {1}}, until an n-bit version is created. The charactercode function prints just the numbers without the braces and commas that are in the output of the addbit function.
Impossible! language (54
58chars)Test run:
(actually I don't know if personal languages are allowed, since Impossible! is still under development, but I wanted to post it anyway..)
In cut-free Prolog (138 bytes if you remove the space after '<<'; submission editor truncates the last line without it):
Ruby - 49 chars
This works for n=100000 with no problem
F#, 152 characters
And here is my Fantom sacrificial offering
(177 char)
Or the expanded version: