Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
29
Task/N-queens-problem/Forth/n-queens-problem-1.fth
Normal file
29
Task/N-queens-problem/Forth/n-queens-problem-1.fth
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
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 recurse r> lowBit-
|
||||
repeat
|
||||
else 1 solutions +! then
|
||||
drop 2drop ;
|
||||
|
||||
: queens ( n -- )
|
||||
0 solutions ! 0 nodes !
|
||||
-1 -1 rot bits try
|
||||
solutions @ . ." solutions, " nodes @ . ." nodes" ;
|
||||
|
||||
8 queens \ 92 solutions, 1965 nodes
|
||||
49
Task/N-queens-problem/Forth/n-queens-problem-2.fth
Normal file
49
Task/N-queens-problem/Forth/n-queens-problem-2.fth
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
\ http://www.forth.org/fd/FD-V02N1.pdf
|
||||
VOCABULARY nqueens ALSO nqueens DEFINITIONS
|
||||
|
||||
8 constant queens
|
||||
|
||||
\ Nqueen solution from FD-V02N1.pdf
|
||||
: 1array CREATE 0 DO 1 , LOOP DOES> SWAP CELLS + ;
|
||||
queens 1array a \ a,b & c: workspaces for solutions
|
||||
queens 2* 1array b
|
||||
queens 2* 1array c
|
||||
queens 1array x \ trial solutions
|
||||
|
||||
: safe ( c i -- n )
|
||||
SWAP
|
||||
2DUP - queens 1- + c @ >R
|
||||
2DUP + b @ >R
|
||||
DROP a @ R> R> * * ;
|
||||
|
||||
: mark ( c i -- )
|
||||
SWAP
|
||||
2DUP - queens 1- + c 0 swap !
|
||||
2DUP + b 0 swap !
|
||||
DROP a 0 swap ! ;
|
||||
|
||||
: unmark ( c i -- )
|
||||
SWAP
|
||||
2DUP - queens 1- + c 1 swap !
|
||||
2DUP + b 1 swap !
|
||||
DROP a 1 swap ! ;
|
||||
|
||||
VARIABLE tries
|
||||
VARIABLE sols
|
||||
|
||||
: .cols queens 0 DO I x @ 1+ 5 .r loop ;
|
||||
: .sol ." Found on try " tries @ 6 .R .cols cr ;
|
||||
|
||||
: try
|
||||
queens 0
|
||||
DO 1 tries +!
|
||||
DUP I safe
|
||||
IF DUP I mark
|
||||
DUP I SWAP x !
|
||||
DUP queens 1- < IF DUP 1+ RECURSE ELSE sols ++ .sol THEN
|
||||
DUP I unmark
|
||||
THEN
|
||||
LOOP DROP ;
|
||||
|
||||
: go 0 tries ! CR 0 try CR sols @ . ." solutions Found, for n = " queens . ;
|
||||
go
|
||||
Loading…
Add table
Add a link
Reference in a new issue