Skip to content

Instantly share code, notes, and snippets.

@jdh30
Created November 21, 2022 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdh30/94950b1e588ce3a3c5b2de46d3bf7a55 to your computer and use it in GitHub Desktop.
Save jdh30/94950b1e588ce3a3c5b2de46d3bf7a55 to your computer and use it in GitHub Desktop.
Find solutions to the n-queens problem
let safe (x1, y1) (x2, y2) =
x1 <> x2 && y1 <> y2 && x2 - x1 <> y2 - y1 && x1 - y2 <> x2 - y1
let rec next n s =
Stack.pop s @
[ None -> None
| Some((qs, ps), s) ->
Stack.pop ps @
[ None -> if Stack.length qs = n then Some(qs, s) else next n s
| Some(q, ps) ->
Stack.push (qs, ps) s
@ Stack.push (Stack.push q qs, Stack.filter (safe q) ps)
@ next n ] ]
let ps n =
for 1 1 n (Stack.empty()) [ps, i ->
for 1 1 n ps [ps, j ->
Stack.push (i, j) ps]]
let tableOf (n, qs) =
let qs = Set.ofStack qs in
Array.init n [i ->
Array.init n [j ->
Html.of(if Set.contains (i+1, j+1) qs then "♕" else "")
@ Html.tag "span" {"style", "font-size: 24px"}
@ Html.tag "td" {"style", "border: 1px solid gray; width: 28px; text-align: center"} ]
@ Html.concat
@ Html.tr ]
@ Html.concat
@ Html.tag "table" {"style", "border: 2px solid black; margin: auto;"}
@ yield
let solutions n = Seq.unfold (next n) (stack{Stack.empty(), ps n})
let f n =
solutions n
@ Seq.first
@ Option.iter [qs -> tableOf(n, qs)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment