-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexamples.fifo
51 lines (41 loc) · 921 Bytes
/
examples.fifo
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
\ -*- forth -*-
\ Various example programs
: fibonacci
dup 0= if
else
dup 1 = if
else
1 - dup fibonacci
swap 1 - fibonacci +
then
then ;
: factorial ( n -- n! )
dup 1 > if
dup 1- factorial *
then ;
: gcd ( a b -- n )
begin dup while tuck mod repeat drop ;
\ adapted from https://rosettacode.org/wiki/N-queens_problem#Forth
variable solutions
variable nodes
: bits ( n -- mask ) 1 swap lshift 1- ;
: lowBit ( mask -- bit ) dup negate and ;
: lowBit- ( mask -- bits ) dup 1- and ;
: next3 ( dl dr f files -- dl dr f dl' dr' f' )
invert >r
2 pick r@ and 2* 1+
2 pick r@ and 2/
2 pick r> and ;
: try ( dl dr f -- )
dup if
1 nodes +!
dup 2over and and
begin ?dup while
dup >r lowBit next3 try r> lowBit-
repeat
else 1 solutions +! then
drop 2drop ;
: queens ( n -- )
0 solutions ! 0 nodes !
-1 -1 rot bits try
solutions @ . nodes @ . ;