Skip to content

Instantly share code, notes, and snippets.

@milang
Created December 20, 2017 07:52
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 milang/f5ffa989e0f31e60aa4cd24ed5db2ad6 to your computer and use it in GitHub Desktop.
Save milang/f5ffa989e0f31e60aa4cd24ed5db2ad6 to your computer and use it in GitHub Desktop.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Input data
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let parse filename =
File.ReadAllLines(filename)
|> Seq.map (fun line -> line |> Array.ofSeq)
|> Array.ofSeq
let data = parse "queries/Advent/Advent2017-day19.txt"
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Problem A + B
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let getMapCell map x y =
if (y < 0 || y >= Array.length map) then None
else
let row = map.[y]
if (x < 0 || x >= Array.length row) then None
else Some row.[x]
let traverse map =
let getMapCell' = getMapCell map
let rec traverse' (x,y) (dx,dy) (message: char list) steps =
let cell = getMapCell' x y
match cell with
| None -> (message,steps)
| Some cellValue ->
match cellValue with
| '|' -> traverse' (x+dx,y+dy) (dx,dy) message (steps+1)
| '-' -> traverse' (x+dx,y+dy) (dx,dy) message (steps+1)
| '+' when dx <> 0 ->
let dy' =
match (getMapCell' x (y-1)) with
| None -> 1
| Some ' ' -> 1
| _ -> -1
traverse' (x,y+dy') (0,dy') message (steps+1)
| '+' when dy <> 0 ->
let dx' =
match (getMapCell' (x-1) y) with
| None -> 1
| Some ' ' -> 1
| _ -> -1
traverse' (x+dx',y) (dx',0) message (steps+1)
| letter when letter >= 'A' && letter <= 'Z' -> traverse' (x+dx,y+dy) (dx,dy) (letter::message) (steps+1)
| ' ' -> (message,steps)
| _ -> raise (InvalidOperationException ("Unknown cell \"" + (string cellValue) + "\""))
let startPositionX = data.[0] |> Array.findIndex ((=) '|')
traverse' (startPositionX,0) (0,1) [] 0
let (message,steps) = traverse data
(message |> List.rev |> Seq.ofList |> Seq.map string |> String.concat "").Dump("Message")
steps.Dump("Steps")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment