// ----------------------------------------------------------------- // nim.txt: Fibonacci Nim, a subtraction game // Concrete Abstractions: Puzzles and Games // (c) 2020, Wolfgang Schreiner, RISC, JKU Linz, Austria // ----------------------------------------------------------------- // See also Buchberger, Lichtenberger 1981: Mathematik für Informatiker I // the size of the heap val N:ℕ; axiom minN ⇔ N ≥ 2; type Num = ℕ[N]; // the minimum of n and the double of i fun double(i:Num,n:Num):Num = let i0 = 2⋅i in if i0 ≤ n then i0 else n; shared system Subtract { var n:Num = N; // size of heap var m:Num = N-1; // maximum to be taken var p:ℕ[1] = 0; // player of next move // show game won invariant n = 0 ⇒ printtrace in ⊤; action take(i:Num) with 1 ≤ i ∧ i ≤ m; { n ≔ n-i; m ≔ double(i,n); p ≔ 1-p; } } // i is a winning move for heap of size n pred win(n:Num,i:Num) ⇔ i = n ∨ (i < n ∧ ¬∃i0:Num with 1 ≤ i0 ∧ i0 ≤ 2⋅i. win(n-i,i0)); // in situation n,m, the current player has a winning strategy pred winnable(n:Num,m:Num) ⇔ ∃i:Num with 1 ≤ i ∧ i ≤ m. win(n,i); // recursively compute a winning move for n,m (-1, if none) multiple fun winr(n:Num,m:Num):ℤ[-1,N] requires n ≥ 1; ensures if winnable(n,m) then result ≥ 0 ∧ win(n,result) else result = -1; = if n ≤ m then n else choose i:Num with 1 ≤ i ∧ i ≤ m ∧ winr(n-i,double(i,n)) = -1 in i else -1; shared system Subtract0 { var n:Num = N; // size of heap var m:Num = N-1; // maximum to be taken var p:ℕ[1] = 0; // player of next move // check that always first player wins invariant n = 0 ⇒ printtrace in p = 1; // ensure that first player has a winning strategy init() with winnable(n,m); { } action take(i:Num) with 1 ≤ i ∧ i ≤ m ∧ (winnable(n,m) ⇒ win(n,i)); { n ≔ n-i; m ≔ double(i,n); p ≔ 1-p; } } // ----------------------------------------------------------------- // end of file // -----------------------------------------------------------------