Skip to content

Instantly share code, notes, and snippets.

@zindel
Created December 3, 2019 02:54
Show Gist options
  • Save zindel/f1ab9417b33efe8cc03133d60a0e7d10 to your computer and use it in GitHub Desktop.
Save zindel/f1ab9417b33efe8cc03133d60a0e7d10 to your computer and use it in GitHub Desktop.
let solve lines =
let program =
lines
|> List.hd
|> CCString.split_on_char ','
|> List.map int_of_string
in
let access () =
let program = Array.of_list program in
let get = Array.get program in
let set ~pos = Array.set program pos in
(get, set)
in
let exec ~noun ~verb =
let (get, set) = access () in
set ~pos:1 noun;
set ~pos:2 verb;
let rec exec pos =
let op = get pos in
let arg1 = get (pos + 1) in
let arg2 = get (pos + 2) in
let res = get (pos + 3) in
match op with
| 1 -> set ~pos:res (get arg1 + get arg2); exec (pos + 4)
| 2 -> set ~pos:res (get arg1 * get arg2); exec (pos + 4)
| 99 -> ()
| _ -> assert false
in
exec 0;
get 0
in
Printf.printf "Part1 = %d\n" (exec ~noun:12 ~verb:2);
let find_noun_verb () =
let rec loop ~noun ~verb =
let res = exec ~noun ~verb in
if res = 19690720 then (noun, verb)
else
let (noun, verb) =
match verb + 1 with
| 100 -> begin match noun + 1 with
| 100 -> assert false
| noun -> (noun, 0)
end
| verb -> (noun, verb)
in loop ~noun ~verb
in
let (noun, verb) = loop ~noun:0 ~verb:0 in
noun * 100 + verb
in
Printf.printf "Part2 = %d\n" @@ find_noun_verb ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment