2012-08-03 18:17:50 -04:00
|
|
|
! Copyright (c) 2012 Anonymous
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
|
|
|
USING: kernel sequences math math.combinatorics formatting io locals ;
|
|
|
|
IN: rosetta-code.n-queens
|
|
|
|
|
|
|
|
! http://rosettacode.org/wiki/N-queens_problem
|
|
|
|
|
|
|
|
! Solve the eight queens puzzle. You can extend the problem to
|
|
|
|
! solve the puzzle with a board of side NxN.
|
|
|
|
|
|
|
|
:: safe? ( board q -- ? )
|
|
|
|
[let q board nth :> x
|
2017-06-01 17:59:35 -04:00
|
|
|
q <iota> [
|
2012-08-03 18:17:50 -04:00
|
|
|
x swap
|
|
|
|
[ board nth ] keep
|
|
|
|
q swap -
|
|
|
|
[ + = not ]
|
|
|
|
[ - = not ] 3bi and
|
|
|
|
] all?
|
|
|
|
] ;
|
|
|
|
|
|
|
|
: solution? ( board -- ? )
|
2017-06-01 17:59:35 -04:00
|
|
|
dup length <iota> [ dupd safe? ] all? nip ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: queens ( n -- l )
|
2017-06-01 17:59:35 -04:00
|
|
|
<iota> all-permutations [ solution? ] filter ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: queens. ( n -- )
|
|
|
|
queens [ [ 1 + "%d " printf ] each nl ] each ;
|