19
\$\begingroup\$

Introduction

XOR is a digital logic gate that implements an exclusive or. Most of the times, this is shown as ^. The four possible outcomes in binary:

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

This can also be seen as addition modulo 2 in binary. In decimal, we need to convert the decimal to binary, 35 = 100011 and 25 = 11001.To compute the XOR value, we place them on top of each other:

100011
 11001 ^
--------
111010  = 58 in decimal

The task: When given an integer value N greater than 1, output an XOR table with the size N + 1. For example, N = 5:

 0 1 2 3 4 5
 1 0 3 2 5 4
 2 3 0 1 6 7
 3 2 1 0 7 6
 4 5 6 7 0 1
 5 4 7 6 1 0

You can see that there is one space in front of each number, because the highest amount in the table has length 1. However, if we take N = 9, we get the following grid:

  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

The highest value has length 2, so the value is right-aligned to length 3 (highest length + 1).

Rules:

  • Leading whitespace is not mandatory, only if used (or not) consistently
  • You must output a table in the form shown above.
  • The padding between columns should be as small as possible
  • This is , so the submission with the least amount of bytes wins!
\$\endgroup\$
  • \$\begingroup\$ How much padding is allowed between columns? Only the minimal possible amount? \$\endgroup\$ – Martin Ender Dec 27 '15 at 16:01
  • \$\begingroup\$ @MartinBüttner Yes, the minimal possible amount. I'll add that to the description. \$\endgroup\$ – Adnan Dec 27 '15 at 16:02
  • \$\begingroup\$ Related codegolf.stackexchange.com/questions/67183/… \$\endgroup\$ – edc65 Dec 27 '15 at 16:13
  • \$\begingroup\$ Looking at the examples output an XOR table with the size N+1 \$\endgroup\$ – edc65 Dec 27 '15 at 16:38
  • \$\begingroup\$ What is the max value for N? ... (for N==1000000 the size of the table would be near 10 Terabyte) \$\endgroup\$ – edc65 Dec 27 '15 at 17:52

21 Answers 21

12
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Compiler working in Octave coming soon... \$\endgroup\$ – Luis Mendo Dec 27 '15 at 18:20
  • \$\begingroup\$ ... well, hopefully. Any idea about this, anyone? \$\endgroup\$ – Luis Mendo Dec 27 '15 at 19:24
  • 5
    \$\begingroup\$ Definitely the right tool for the job. +1 \$\endgroup\$ – a spaghetto Dec 27 '15 at 21:55
  • 1
    \$\begingroup\$ After some tweaking, the compiler seems to work in Octave (4.0.0). I need to do more testing, but all the programs I've tried, including this one, work. While I post a new release, here's a link to the current GitHub commit to run this code in Octave. The language hasn't changed (it's still release 5.0.0), so it's earlier than this challenge \$\endgroup\$ – Luis Mendo Dec 28 '15 at 1:44
6
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6) 120 122

Edit 2 bytes saved thx ETHproductions

An anonymous function. Note: the number in the table are limited to 7 digits, that is more than reasonable given the overall size of a table allowing for bigger numbers

Now I should find a shorter way to get the max columns size, avoiding logarithms

n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>`       ${i^j}`.slice(~m)).join``).join`
`

Test

f=n=>(a=Array(n+1).fill(-~Math.log10(2<<Math.log2(n)))).map((m,i)=>a.map((z,j)=>`       ${i^j}`.slice(~m)).join``).join`\n`

function update() {
  var v=+I.value
  O.textContent = f(v)
}  

update()
N: <input id=I type=number value=9 oninput='update()'>
<pre id=O></pre>

\$\endgroup\$
  • \$\begingroup\$ Awesome, love the use of ~m to capture an extra space. Using a template string can save two bytes: (z,j)=>`(7 spaces)${i^j}`.slice(~m) \$\endgroup\$ – ETHproductions Dec 27 '15 at 20:17
  • \$\begingroup\$ @ETHproductions 1) good suggestion, thanks 2) how did you manage to put a ... (I cannot even ask it) ... a char(96) inside 2 char(96)? \$\endgroup\$ – edc65 Dec 27 '15 at 20:44
  • \$\begingroup\$ Aha, you just use multiple backticks, like so: (ignore this padding) ``abc`def`` (ignore this too) Shows up like this: abc`def \$\endgroup\$ – ETHproductions Dec 27 '15 at 21:11
3
\$\begingroup\$

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

C, 103 bytes

Y(n){int i,j=n++;char*f="%2u";while(j/=8)++f[1];for(;j<n;++j,puts(""))for(i=0;i<n;++i)printf(f,i^j);}
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! For what I can see, your answer, as unfortunately many others here, completey miss the column alignment point. \$\endgroup\$ – edc65 Dec 28 '15 at 19:01
  • \$\begingroup\$ Try it with input 5 (too much space between columns) or 65 (too few) \$\endgroup\$ – edc65 Dec 28 '15 at 19:05
  • \$\begingroup\$ this would be ok at last until 512, at last here... \$\endgroup\$ – Ros Dec 29 '15 at 6:26
3
\$\begingroup\$

Jelly, non-competing

7 bytes This answer is non-competing, since it uses features that postdate the challenge.

0r©^'®G

Try it online!

How it works

0r©^'®G  Main link. Input: n (integer)

0r       Range; yield [0, ..., n].
  ©      Save the range in the register.

     ®   Yield the range from the register.
   ^'    XOR each integer in the left argument with each integer in the right one.
      G  Grid; separate rows by newlines, columns by spaces, with a fixed width for
         all columns. Since the entries are numeric, align columns to the right.
\$\endgroup\$
  • 2
    \$\begingroup\$ Congrats on your 1000th answer :) \$\endgroup\$ – Adnan Mar 30 '16 at 17:38
3
\$\begingroup\$

R, 38 bytes

Usually R requires a lot of bytes just to format the output. In this case it's quite the opposite. outer which is usually refers to the outer product of two arrays, can when supplied a function perform this across the margins of the vectors. In this case, we apply the bitwise XOR function bitwXor.

names(x)=x=1:scan();outer(x,x,bitwXor)
\$\endgroup\$
2
\$\begingroup\$

CJam, 29 27 bytes

ri:X),_ff{^s2X2b,#s,)Se[}N*

Test it here.

Explanation

ri      e# Read input and convert to integer.
:X      e# Store in X.
),      e# Get range [0 1 ... X].
_ff{    e# Nested map over all repeated pairs from that range...
  ^     e#   XOR.
  s     e#   Convert to string.
  2     e#   Push 2.
  X2b,  e#   Get the length of the base-2 representation of X. This is the same as getting
        e#   getting the base-2 integer logarithm and incrementing it.
  #     e#   Raise 2 to that power. This rounds X up to the next power of 2.
  s,    e#   Convert to string and get length to determine column width.
  )     e#   Increment for additional padding.
  Se[   e#   Pad string of current cell from the left with spaces.
}
N*      e# Join with linefeeds.
\$\endgroup\$
  • \$\begingroup\$ Well, that was quick haha \$\endgroup\$ – Adnan Dec 27 '15 at 16:06
2
\$\begingroup\$

MathCAD, 187 Bytes

enter image description here

MathCAD handles built in tables easily - but has absolutely no bitwise Xor, nor decimal to binary or binary to decimal converters. The for functions iterate through the possible values. The i, a2, Xa and Xb place hold. The while loop actively converts to binary, and while converting to binary also performs the xor function (the little cross with the circle around it). It stores the binary number in a base-10 number consisting of 0's and 1's. This is then converted before being stored in the M matrix via the summation function.

This can easily be golfed down (if only by swapping out the placeholders for shorter ones), but I figured I'd post it and see if anyone can golf down the binary to decimal converter more than anything else.

\$\endgroup\$
2
\$\begingroup\$

k4, 50 bytes

{-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;}

E.g.:

  {-1@" "/:'(-|//#:''x)$x:$2/:''~x=/:\:x:0b\:'!1+x;}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
\$\endgroup\$
2
\$\begingroup\$

C, 149 bytes

int i=0,j,n,k=2;char b[256];scanf("%d",&n);while((k*=2)<=n);k^=k-1;while(i++<=n&&putchar(10))for(j=0;j<=n;j++)printf(" %*d",sprintf(b,"%d",k),i-1^j);
---------

Detailed

#include <stdio.h>

int main()
{
    int i=0, j, n, k=2;
    char b[256] = { 0 };

    scanf("%d", &n);

    // find max xor value in the table
    while((k*=2)<=n); k^=k-1;

    printf("> %d ~ %d", k, sprintf(b,"%d",k));

    while(i++ <= n && putchar(10))
    {
        for(j = 0; j <= n;j++)
        {
            printf(" %*d", sprintf(b,"%d",k), (i-1)^j);
        }
    }

    return 0;
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Just like your java post, there is no attempt to align correctly the columns. That's the only difficult part of this challenge. This code gives wrong output when input < 8 or > 64. \$\endgroup\$ – edc65 Dec 28 '15 at 9:16
  • \$\begingroup\$ @edc65 I found out how to align, the max xor value is binary 11..1 to the significant one in the input value n, can be done by first finding the nearest power of 2, then xor it with the previous number, 0001 xor 1110 = 1111 \$\endgroup\$ – Khaled.K Dec 29 '15 at 7:43
  • \$\begingroup\$ Good, you are on the right track now. Still, you should test more: the loop with k gives wrong result for n=8 (and your short answer does not initialize the local variable i to 0) \$\endgroup\$ – edc65 Dec 29 '15 at 8:12
  • \$\begingroup\$ This simpler loop should do: for(k=1;k<=n;)k*=2;k--;. Now I see that is much shorter than my C attempt to the same (mine is better for performance, but performance does not matter in this challenge) \$\endgroup\$ – edc65 Dec 29 '15 at 8:16
  • \$\begingroup\$ @edc65 you need to do 2^k xor 2^k -1 for max{2^k<=n} or 2^k -1 for min{2^k>=n}. to get all 11..1 in there \$\endgroup\$ – Khaled.K Dec 29 '15 at 8:30
2
\$\begingroup\$

Python 3, 133 131 bytes

import math
n=int(input())
r,p=range(n+1),print
for y in r:[p(end='%%%dd '%len(str(2**int(math.log2(n)+1)-1))%(x^y))for x in r];p()
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 108 bytes

StringRiffle[Thread[Map[ToString,a=Array[BitXor,{#,#}+1,0],{2}]~StringPadLeft~IntegerLength@Max@a],"
"," "]&

Disregard the error, it's just Thread not knowing what it's doing.

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

Emacs Lisp, 193 bytes

(defun x(n)(set'a 0)(set'n(1+ n))(while(< a n)(set'b 0)(while(< b n)(princ(format(format"%%%ss "(ceiling(log(expt 2(ceiling(log n 2)))10)))(logxor a b)))(set'b(1+ b)))(set'a(1+ a))(message"")))

Ungolfed:

(defun x(n)
  (set'a 0)
  (set'n(1+ n))
  (while(< a n)
    (set'b 0)
    (while(< b n)
      (princ
        (format
          ;; some format string magic to get the length of the longest
          ;; possible string as a format string
          (format "%%%ss " (ceiling(log(expt 2(ceiling(log n 2)))10)))
          (logxor a b)))
      (set'b(1+ b)))
    (set'a(1+ a))
    ;; new line
    (message"")))

The output is sent to the *Message* buffer, which would be stdout if x were to be used inside a script.

(x 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
\$\endgroup\$
1
\$\begingroup\$

Python 2, 114 bytes

It took some looking to find a way to do variable-width padding in .format() (some, not a lot) and get it right-adjusted, but I think I've got it all to spec now. Could use more golfing in that width calculation though.

N=input()+1
for i in range(N):print''.join(' {n:>{w}}'.format(w=len(`2**(len(bin(N))-2)`),n=i^r)for r in range(N))
\$\endgroup\$
1
\$\begingroup\$

Caché ObjectScript, 127 bytes

x(n)s w=$L(2**$bitfind($factor(n),1,100,-1))+1 f i=0:1:n { w $j(i,w) } f i=1:1:n { w !,$j(i,w) f j=1:1:n { w $j($zb(i,j,6),w) } }

Detailed:

x(n)
 set w=$Length(2**$bitfind($factor(n),1,100,-1))+1
 for i=0:1:n {
     write $justify(i,w)
 }
 for i=1:1:n {
     write !,$justify(i,w)
     for j=1:1:n {
         write $justify($zboolean(i,j,6),w)
     }

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

Pyke, 8 bytes (non-competing)

hD]UA.&P

Explanation:

         - auto-add eval_or_not_input() to the stack
h        - increment the input
 D]      - Create a list containing [inp+1, inp+1]
   U     - Create a 2d range 
    A.^  - Deeply apply the XOR function to the range
       P - print it out prettily

Try it here

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

Python 2, 77 bytes

n=input()+1
t=range(n)
for i in t: print "%3d"*n % tuple([x^i for x in t])
\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! For what I can see, your answer, as unfortunately many others here, completey misses the column alignment point. \$\endgroup\$ – cat Mar 30 '16 at 14:11
0
\$\begingroup\$

J, 10 bytes

XOR/~@,~i.

Try it online!

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

Excel VBA, 95 bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the console.

For y=0To[A1]:For x=0To[A1]:z=x Xor y:?Spc([Len(2^-Int(-Log(A1,2)))]-Len(z))Str(z);:Next:?:Next
\$\endgroup\$
0
\$\begingroup\$

Small Basic, 499 bytes

A script that takes input from the TextWindow object and outputs to the same

a=TextWindow.Read()
For y=0To a
For x=0To a
n=x
b()
z1=z
n=y
b()
l=Math.Max(Array.GetItemCount(z),Array.GetItemCount(z1))
o=0
For i=1To l
If z1[i]<>z[i]And(z[i]=1Or z1[i]=1)Then
z2=1
Else 
z2=0
EndIf
o=o+z2*Math.Power(2,i-1)
EndFor
TextWindow.Write(Text.GetSubText("      ",1,Text.GetLength(Math.Power(2,Math.Ceiling(Math.Log(a)/Math.Log(2))))-Text.GetLength(o))+o+" ")
EndFor
TextWindow.WriteLine("")
EndFor
Sub b
z=0
c=0  
While n>0
c=c+1
z[c]=Math.Remainder(n,2)
n=Math.Floor(n/2)
EndWhile
EndSub

Try it at SmallBasic.com Uses Silverlight and thus must be run in IE or Edge

Select the black console, then type input integer and press Enter.

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