Skip to content

Instantly share code, notes, and snippets.

@leviroth
Created December 3, 2019 01:30
Advent of Code 2019 - Day 2 - just the essentials
open! Core
let run_program program =
let get_indirect index = program.(program.(index)) in
let set_indirect index value = program.(program.(index)) <- value in
let rec solve index =
let apply_simple_op operator =
let value = operator (get_indirect (index + 1)) (get_indirect (index + 2)) in
set_indirect (index + 3) value;
solve (index + 4)
in
match program.(index) with
| 1 -> apply_simple_op ( + )
| 2 -> apply_simple_op ( * )
| 99 -> ()
| opcode -> raise_s [%message "Unexpected opcode" (index : int) (opcode : int)]
in
solve 0
;;
let run_program_with_inputs program first second =
let program = Array.of_list program in
program.(1) <- first;
program.(2) <- second;
run_program program;
program.(0)
;;
let solve_part_1 program = run_program_with_inputs program 12 2
let target_output = 19690720
let solve_part_2 program =
let zig_zag =
Sequence.unfold_step ~init:(0, 0) ~f:(fun (first, second) ->
match first <= second with
| true -> Skip (first + 1, 0)
| false -> Yield ((first, second), (first, second + 1)))
in
let noun, verb =
Sequence.find zig_zag ~f:(fun (first, second) ->
run_program_with_inputs program first second = target_output)
|> Option.value_exn
in
(noun * 100) + verb
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment