Produce an XOR table

MATL, 10 bytes

0i2$:tXgZ~

The compiler (and in particular this program) now seems to work in Octave, although it still needs some refinement. You can provisionally use this GitHub commit.

Edit (Mar 30 '16): Try it online!

Example

>> matl 0i2$:tXgZ~
> 9
0  1  2  3  4  5  6  7  8  9
1  0  3  2  5  4  7  6  9  8
2  3  0  1  6  7  4  5 10 11
3  2  1  0  7  6  5  4 11 10
4  5  6  7  0  1  2  3 12 13
5  4  7  6  1  0  3  2 13 12
6  7  4  5  2  3  0  1 14 15
7  6  5  4  3  2  1  0 15 14
8  9 10 11 12 13 14 15  0  1
9  8 11 10 13 12 15 14  1  0

Explanation

0i2$:       % vector 0, 1, 2, ... up to input number
t           % duplicate
Xg          % nd-grid
Z~          % bitxor

Bash + BSD utils, 45

eval echo \$[{0..$1}^{0..$1}]|rs -jg1 $[$1+1]

I've been waiting a long time to find a use for rs. This seems to be a good one. rs may need to be installed on Linux systems. But it runs right out of the box on OS X.

  • $1 expands to N, and thus echo \$[{0..$1}^{0..$1}] expands to echo $[{0..N}^{0..N}]
  • This is then evaled:
  • The brace expansion expands to $[0^0] $[0^1] $[0^2] ... $[0^N] ... $[N^N]
  • This is a series of xor arithmetic expansions which expand to one line of terms
  • rs (reshape) reshapes this line to N+1 rows. -j right justifies, and -g1 gives a gutter-width of 1. This ensures the final output table has minimal width between columns.

I've tested up to N=1000, which took 3.8 seconds. Large N is theoretically possible, though bash will run out of memory at some point with the (N+1)² memory usage of the brace expansion.


C, 114 128 152

Edit Simplified space counting, inspired by the work of Khaled A Khunaifer

A C function that follows the specs.

T(n){int i=0,j,x=1,d=0;while(x<=n)x+=x,++d;for(;i<=n;i++)for(j=0;j<=n;j++)printf("%*d%c",d*3/10+1,i^j,j<n?32:10);}

Try it insert n as input, default 9

Less golfed

T(n)
{
   int i=0, j, x=1,d=0;
   while(x<=n) x+=x,++d; // count the digits
   // each binary digit is approximately 0.3 decimal digit
   // this approximation is accurate enough for the task
   for(;i<=n;i++)
     for(j=0;j<=n;j++)
       printf("%*d%c",d*3/10+1,
              i^j,
              j < n ? 32:10); // space between columns, newline at end
}