Created
April 20, 2012 15:59
-
-
Save komamitsu/2429902 to your computer and use it in GitHub Desktop.
N Queen problem in OCaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let ($) f g = f g | |
let safe n q qs = | |
let (qx, qy) = q in | |
if List.exists begin | |
fun (x, y) -> qx = x || qy = y | |
end qs then false | |
else | |
let rec row_iter iy = | |
if iy >= n then true | |
else | |
let diff = iy - qy in | |
if List.exists begin | |
fun (x, y) -> | |
iy = y && (qx + diff = x || qx - diff = x) | |
end qs then false | |
else row_iter $ iy + 1 | |
in | |
row_iter 0 | |
let find n = | |
let rec iter_row y qss = | |
if y >= n then qss | |
else | |
iter_row (y + 1) $ | |
List.fold_left begin | |
fun new_qss qs -> | |
let rec iter_col x qss = | |
if x >= n then qss | |
else | |
let q = (x, y) in | |
iter_col (x + 1) $ if safe n q qs then (q::qs)::qss else qss | |
in | |
iter_col 0 new_qss | |
end [] qss | |
in | |
iter_row 0 [[]] | |
let _ = | |
List.iter begin | |
fun qs -> | |
print_endline "------------------------------------------------------"; | |
List.iter begin | |
fun (x, y) -> Printf.printf "(%d, %d) " x y | |
end qs; | |
print_newline () | |
end $ find 8 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ocaml nqueen.ml | |
------------------------------------------------------ | |
(2, 7) (4, 6) (1, 5) (7, 4) (5, 3) (3, 2) (6, 1) (0, 0) | |
------------------------------------------------------ | |
(2, 7) (5, 6) (3, 5) (1, 4) (7, 3) (4, 2) (6, 1) (0, 0) | |
------------------------------------------------------ | |
(4, 7) (1, 6) (3, 5) (6, 4) (2, 3) (7, 2) (5, 1) (0, 0) | |
------------------------------------------------------ | |
(3, 7) (1, 6) (6, 5) (2, 4) (5, 3) (7, 2) (4, 1) (0, 0) | |
------------------------------------------------------ | |
: | |
: | |
------------------------------------------------------ | |
(4, 7) (6, 6) (1, 5) (5, 4) (2, 3) (0, 2) (3, 1) (7, 0) | |
------------------------------------------------------ | |
(3, 7) (6, 6) (4, 5) (1, 4) (5, 3) (0, 2) (2, 1) (7, 0) | |
------------------------------------------------------ | |
(5, 7) (2, 6) (4, 5) (6, 4) (0, 3) (3, 2) (1, 1) (7, 0) | |
------------------------------------------------------ | |
(5, 7) (3, 6) (6, 5) (0, 4) (2, 3) (4, 2) (1, 1) (7, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment