Skip to content

Instantly share code, notes, and snippets.

@danyx23
Created October 2, 2019 15:46
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 danyx23/1d74713949e2c3958dc47c2e521600a9 to your computer and use it in GitHub Desktop.
Save danyx23/1d74713949e2c3958dc47c2e521600a9 to your computer and use it in GitHub Desktop.
Simple Maze Solver in F#
let labyrinthString = """xxxxxxx
x x
x x x x
x x x
x xxx x
x x
xxxxxxx"""
let labyrinth =
labyrinthString.Split("\n")
|> Array.map (fun line -> line.ToCharArray())
let dimensions =
labyrinth.[0].Length, labyrinth.Length
let startPos = (fst dimensions /2, snd dimensions / 2)
let printLabyrinth (lab : char array array) =
for row in lab do
printfn "%s" (System.String(row))
printLabyrinth labyrinth
let markPosition lab (x, y) =
lab
|> Array.mapi (fun i row -> if i = y then row |> Array.mapi (fun j c -> if j = x then 'o' else c) else row)
type FieldType =
| Free
| Wall
| Visited
| Outside
let rec findWayOut lab (x, y) =
let walkedLab = markPosition lab (x, y)
let checkPos (checkX, checkY) =
if checkX < 0 || checkX > fst dimensions ||
checkY < 0 || checkY > snd dimensions then
Outside
else
match lab.[checkY].[checkX] with
| 'x' -> Wall
| 'o' -> Visited
| ' ' -> Free
| _ -> failwith "Unkown labyrinth character"
let neighbours =
seq {
yield (x-1, y)
yield (x, y+1)
yield (x+1, y)
yield (x, y-1)
}
neighbours
|> Seq.choose (fun field ->
match checkPos field with
| Outside -> Some walkedLab
| Visited -> None
| Wall -> None
| Free -> findWayOut walkedLab field )
|> Seq.tryHead
let maybeWayOut = findWayOut labyrinth startPos
match maybeWayOut with
| Some wayOut -> printLabyrinth wayOut
| None -> printfn "No way found!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment