Skip to content

Instantly share code, notes, and snippets.

@ebresafegaga
Last active November 18, 2020 20:42
Show Gist options
  • Save ebresafegaga/afdac27f6f323d0064eb9610bbc64390 to your computer and use it in GitHub Desktop.
Save ebresafegaga/afdac27f6f323d0064eb9610bbc64390 to your computer and use it in GitHub Desktop.
N Queens puzzle in OCaml
type pos = Position of int * int
let noAttack (Position (x, y)) (Position (i, j)) =
x <> i && y <> j && abs (x-i) <> abs (y-j)
let rec range n m =
if m < n
then []
else n :: range (n+1) m
let gen row =
range 1 8
|> List.map (fun column -> Position (row, column))
let safe n allegedSolution = match allegedSolution with
| imposter :: solutions ->
List.for_all (fun pos -> noAttack pos imposter) solutions
| [] -> false
let rec queens = function
| 0 -> [[]]
| n ->
queens (n-1)
|> List.map (fun solution -> List.map (fun imposter -> imposter :: solution) (gen n))
|> List.concat
|> List.filter (safe n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment