Skip to content

Instantly share code, notes, and snippets.

@hickford
Created May 10, 2018 13:57
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 hickford/4690235a459903c09d21d4fcedebf91f to your computer and use it in GitHub Desktop.
Save hickford/4690235a459903c09d21d4fcedebf91f to your computer and use it in GitHub Desktop.
let check rows =
// test if any queens are threatening each other
let n = rows |> Seq.length
let areDistinct = Seq.distinct >> Seq.length >> (=) n
let forwardDiagonals = rows |> Seq.mapi (+)
let backDiagonals = rows |> Seq.mapi (-)
rows |> areDistinct && forwardDiagonals |> areDistinct && backDiagonals |> areDistinct
let solve n =
// solve n-queens problem by generating random solutions
match n with
| 2 | 3 -> None // known to be impossible
| _ ->
let r = System.Random()
let permute =
let projection _ = r.Next()
List.sortBy projection
Seq.initInfinite (fun _ -> permute [0..n-1]) |> Seq.tryFind check
let mutable verbose = false
let solve2 n =
// solve n-queens problem by backtracking
let rec inner state =
match state with
| Some rows when List.length rows < n ->
if verbose then printfn "%A" rows
let prepend x = x :: rows
let partials = [0..n-1] |> Seq.map prepend |> Seq.filter check
partials |> Seq.map (Some >> inner) |> Seq.tryFind Option.isSome |> Option.flatten
| _ -> state
Some [] |> inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment