N-queens problem: Difference between revisions

→‎Tcl: Added implementation
(initial version with OCaml)
 
(→‎Tcl: Added implementation)
Line 65:
Gc.set ({(Gc.get ()) with Gc.space_overhead = 500}); (* May help except with an underRAMed system *)
queens (int_of_string Sys.argv.(1));;</lang>
 
=={{header|Tcl}}==
This solution is based on the [[C]] version on [[wp:Eight queens puzzle solutions#C|wikipedia]]. By default it solves the 8-queen case; to solve for any other number, pass ''N'' as an extra argument on the script's command line (see the example for the 6 case, which has anomalously few solutions).
 
{{works with|Tcl|8.5}}
<lang tcl>package require Tcl 8.5
 
proc unsafe {y} {
global b
set x [lindex $b $y]
for {set i 1} {$i <= $y} {incr i} {
set t [lindex $b [expr {$y - $i}]]
if {$t==$x || $t==$x-$i || $t==$x+$i} {
return 1
}
}
return 0
}
 
proc putboard {} {
global b s N
puts "\n\nSolution #[incr s]"
for {set y 0} {$y < $N} {incr y} {
for {set x 0} {$x < $N} {incr x} {
puts -nonewline [expr {[lindex $b $y] == $x ? "|Q" : "|_"}]
}
puts "|"
}
}
 
proc main {n} {
global b N
set N $n
set b [lrepeat $N 0]
set y 0
lset b 0 -1
while {$y >= 0} {
lset b $y [expr {[lindex $b $y] + 1}]
while {[lindex $b $y] < $N && [unsafe $y]} {
lset b $y [expr {[lindex $b $y] + 1}]
}
if {[lindex $b $y] >= $N} {
incr y -1
} elseif {$y < $N-1} {
lset b [incr y] -1;
} else {
putboard
}
}
}
 
main [expr {$argc ? int(0+[lindex $argv 0]) : 8}]</lang>
Sample output:
<pre>$ tclsh8.5 8queens.tcl 6
 
Solution #1
|_|Q|_|_|_|_|
|_|_|_|Q|_|_|
|_|_|_|_|_|Q|
|Q|_|_|_|_|_|
|_|_|Q|_|_|_|
|_|_|_|_|Q|_|
 
 
Solution #2
|_|_|Q|_|_|_|
|_|_|_|_|_|Q|
|_|Q|_|_|_|_|
|_|_|_|_|Q|_|
|Q|_|_|_|_|_|
|_|_|_|Q|_|_|
 
 
Solution #3
|_|_|_|Q|_|_|
|Q|_|_|_|_|_|
|_|_|_|_|Q|_|
|_|Q|_|_|_|_|
|_|_|_|_|_|Q|
|_|_|Q|_|_|_|
 
 
Solution #4
|_|_|_|_|Q|_|
|_|_|Q|_|_|_|
|Q|_|_|_|_|_|
|_|_|_|_|_|Q|
|_|_|_|Q|_|_|
|_|Q|_|_|_|_|</pre>
Anonymous user