1
(***********************************************************************)
5
(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
7
(* Copyright 2001 Institut National de Recherche en Informatique et *)
8
(* en Automatique. All rights reserved. This file is distributed *)
9
(* only by permission. *)
11
(***********************************************************************)
13
(* E I G H T Q U E E N S
15
The Eight Queens Program tail recursive version.
22
let rec loop accu = function
24
| x :: l -> loop (f x :: accu) l in
27
let rec interval n m =
28
if n > m then [] else n :: interval (n + 1) m;;
30
let rev_append l1 l2 =
31
let rec loop accu = function
33
| h :: t -> loop (h :: accu) t in
36
let filter_append p l l0 =
37
let rec loop accu = function
39
| h :: t -> if p h then loop (h :: accu) t else loop accu t in
40
let rev_res = loop [] l in
41
rev_append rev_res l0;;
44
let rec loop accu = function
46
| h :: t -> loop (f h accu) t in
49
let rec safe x d = function
52
x <> h && x <> h + d && x <> h - d && safe x (d + 1) t;;
56
| h :: t -> safe h 1 t;;
58
let find_solutions size =
59
let line = interval 1 size in
61
if n = 0 then [[]] else
63
(fun b -> filter_append ok (map (fun q -> q :: b) line))
67
(* 2. Printing results. *)
69
let print_solutions size solutions =
70
let sol_num = ref 1 in
73
Printf.printf "\nSolution number %i\n" !sol_num;
74
sol_num := !sol_num + 1;
78
while !count <= size do
79
if !count = line then print_string "Q " else print_string "- ";
86
let print_result size =
87
let solutions = find_solutions size in
88
let sol_num = List.length solutions in
89
Printf.printf "The %i queens problem has %i solutions.\n" size sol_num;
92
print_string "Do you want to see the solutions <n/y> ? "; read_line () in
93
if pr = "y" then print_solutions size solutions;;
95
(* 3. Main program. *)
99
print_string "Chess boards's size ? "; read_int () in
102
if !Sys.interactive then () else queens ();;