sourcelibs/Bits/demos/nim.xtl
1⍝!/usr/bin/env xetal
2⍝# Nim: heaps of counters; take any number from one heap; whoever takes
3⍝# the last counter wins. The winning move makes the xor of the heaps
4⍝# (the nim-sum) zero, worked out for every heap at once.
5⍝# Run with "just demo Bits nim".
6
7ᵇ⁼u̲se< "Bits"
8heaps ← 3 4 5
9nimsum ← (f̲irst heaps) ᵇx̲or (f̲irst 1 d̲rop heaps) ᵇx̲or f̲irst 2 d̲rop heaps
10nimsum ⍝ not 0: the player to move can win
11
12⍝ Each heap brought to heap xor nim-sum; a move where that is smaller.
13target ← heaps ᵇx̲or nimsum
14target
15(target < heaps) r̲eplicate r̲ange 3 ⍝ the heaps a winning move can use
16
17⍝ The move: heap 1 from 3 down to 1. In binary, a row per heap, every
18⍝ column then holds an even number of ones: the nim-sum is 0.
19after ← heaps − 2 × (r̲ange 3) = 1
203 ᵇb̲its after
21(f̲irst after) ᵇx̲or (f̲irst 1 d̲rop after) ᵇx̲or f̲irst 2 d̲rop after