]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/n-queens/n-queens.factor
factor: trim using lists
[factor.git] / extra / rosetta-code / n-queens / n-queens.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences math math.combinatorics formatting io ;
4 IN: rosetta-code.n-queens
5
6 ! http://rosettacode.org/wiki/N-queens_problem
7
8 ! Solve the eight queens puzzle. You can extend the problem to
9 ! solve the puzzle with a board of side NxN.
10
11 :: safe?  ( board q -- ? )
12     [let q board nth :> x
13       q <iota> [
14          x swap
15          [ board nth ] keep
16          q swap -
17            [ + = not ]
18            [ - = not ] 3bi and
19       ] all?
20     ] ;
21
22 : solution? ( board -- ? )
23     dup length <iota> [ dupd safe? ] all? nip ;
24
25 : queens ( n -- l )
26     <iota> all-permutations [ solution? ] filter ;
27
28 : queens. ( n -- )
29     queens [ [ 1 + "%d " printf ] each nl ] each ;