Skip to content

Instantly share code, notes, and snippets.

@sidharthkuruvila
Created December 9, 2020 23:50
Show Gist options
  • Save sidharthkuruvila/6c9e7f96647d343f3e0dbb009155d7c6 to your computer and use it in GitHub Desktop.
Save sidharthkuruvila/6c9e7f96647d343f3e0dbb009155d7c6 to your computer and use it in GitHub Desktop.
Advent of code
open Core;;
let s = {|nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
|};;
let s = In_channel.read_all "input.txt" |> String.strip;;
let code = s
|> String.strip
|> String.split ~on:'\n'
|> List.map ~f:(fun l ->
let [instr; count] = String.split ~on:' ' l in
(instr, int_of_string count))
|> List.to_array;;
let run code =
let visited = Array.create ~len:(Array.length code) false in
let rec loop i acc =
if visited.(i) then
acc
else begin
visited.(i) <- true;
match Array.get code i with
| ("nop", _) -> loop (i + 1) acc
| ("acc", n) -> loop (i + 1) (acc + n)
| ("jmp", n) -> loop (i + n) acc end in
loop 0 0;;
run code;;
let option_or v ~alt =
match v with
| Some _ -> v
| None -> alt ();;
let run code =
let rec loop i acc visited switched =
if i >= Array.length code then
Some acc
else if visited.(i) then
None
else begin
visited.(i) <- true;
(if not switched then
match Array.get code i with
| ("nop", n) -> loop (i + n) acc (Array.copy visited) true
| ("acc", n) -> None
| ("jmp", _) -> loop (i + 1) acc (Array.copy visited) true
else None)
|> option_or ~alt:(fun _ ->
match Array.get code i with
| ("nop", _) -> loop (i + 1) acc visited switched
| ("acc", n) -> loop (i + 1) (acc + n) visited switched
| ("jmp", n) -> loop (i + n) acc visited switched)
end in
loop 0 0 (Array.create ~len:(Array.length code) false) false;;
run start;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment