aboutsummaryrefslogtreecommitdiff
path: root/challenge-104/paulo-custodio/forth/ch-2.fs
blob: dd77345bf09179da331710414b5b46fc4269d46e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#! /usr/bin/env gforth

\ Challenge 104
\
\ TASK #2 � NIM Game
\ Submitted by: Mohammad S Anwar
\ Write a script to simulate the NIM Game.
\
\ It is played between 2 players. For the purpose of this task, let assume you
\ play against the machine.
\
\ There are 3 simple rules to follow:
\
\ a) You have 12 tokens
\ b) Each player can pick 1, 2 or 3 tokens at a time
\ c) The player who picks the last token wins the game

require random.fs

0 CONSTANT A
1 CONSTANT B
12 CONSTANT tokens
100000 CONSTANT runs

: .num              ( n -- )
    0 U.R
;

: play-to-win   { t -- n }
    t 3 <=      IF t EXIT THEN
    t 4 MOD 0=  IF 1 EXIT THEN
    t 5 MOD 0=  IF 1 EXIT THEN
    t 6 MOD 0=  IF 2 EXIT THEN
    t 7 MOD 0=  IF 3 EXIT THEN
    t 9 MOD 0=  IF 2 EXIT THEN
    t 11 MOD 0= IF 2 EXIT THEN
    1 ;

: play-random   { t -- n }
    3 random 1+ ;

' play-to-win VALUE play-xt

CREATE wins 0 , 0 ,

: wins[]    ( i -- addr )
    CELLS wins + ;

: match     { T -- n }  \ run match, return player that won
    BEGIN
        \ player A
        T play-to-win  T SWAP - TO T        \ plays
        T 1 < IF A EXIT THEN                \ A wins

        \ player B
        T play-xt EXECUTE  T SWAP - TO T    \ plays
        T 1 < IF B EXIT THEN                \ B wins
    AGAIN ;

: matches   ( runs -- )     \ run matches, compute wins
    0. wins 2!
    0 ?DO
        tokens match
        wins[] 1 SWAP +!
    LOOP ;

: go
    NEXT-ARG DUP 0= THROW
    S" random" COMPARE 0= IF
        ['] play-random TO play-xt
    ELSE
        ['] play-to-win TO play-xt
    THEN
    runs matches

    ." A wins "
    A wins[] @ 100 *
    A wins[] @  B wins[] @  +  /  .num
    ." % of the matches." CR ;

go BYE