Last active
December 8, 2016 09:23
-
-
Save mikaelbr/f2583afe61ec8fa119f1dc65c6ffdd36 to your computer and use it in GitHub Desktop.
This file contains 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
#load "str.cma";; | |
let read_file filename = | |
let lines = ref [] in | |
let chan = open_in filename in | |
try | |
while true; do | |
lines := input_line chan :: !lines | |
done; !lines | |
with End_of_file -> | |
close_in chan; | |
List.rev !lines ;; | |
let destruct_line pos line : (string option * int) = | |
let r = Str.regexp "walk \\([0-9]+\\) meters \\([a-z]+\\)" in | |
if (Str.string_match r line pos) then | |
let meters = Str.matched_group 1 line in | |
let direction = Str.matched_group 2 line in | |
(Some direction, int_of_string meters) | |
else | |
(None, 0);; | |
let rec solve (x, y) a = | |
let n = match List.hd a with | |
| (Some "north", m) -> (x + m, y) | |
| (Some "south", m) -> (x - m, y) | |
| (Some "west", m) -> (x, y + m) | |
| (Some "east", m) -> (x, y - m) | |
| _ -> (0, 0) in | |
let t = List.tl a in | |
match t with | |
| [] -> n | |
| _ -> solve n t;; | |
read_file "data.dat" | |
|> List.map (destruct_line 0) | |
|> solve (0, 0) | |
|> (fun (x, y) -> Printf.printf "(%d,%d)" x y);; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment