Last active
November 18, 2020 20:42
-
-
Save ebresafegaga/afdac27f6f323d0064eb9610bbc64390 to your computer and use it in GitHub Desktop.
N Queens puzzle in OCaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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