Created
December 5, 2019 03:42
-
-
Save ragiragi/667347367bc8bbaf66b75f314c8a4f77 to your computer and use it in GitHub Desktop.
Advent of Code 2019, Day 2 part 1
This file contains hidden or 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
| open Base | |
| open Stdio | |
| type program = (int array) * int | |
| type opcode = Add | Multiply | Halt | |
| let opcode_of_int = function | |
| | 1 -> Add | |
| | 2 -> Multiply | |
| | 99 -> Halt | |
| | _ -> assert false | |
| let current_opcode ((codes, pos) : program) = | |
| Array.get codes pos |> opcode_of_int | |
| let final_result (codes, _) = Array.get codes 0 | |
| let execute (program : program) (f : int -> int -> int) : program = | |
| let (codes, pos) = program in | |
| let at = Array.get codes in | |
| let v1 = at (at (pos + 1)) in | |
| let v2 = at (at (pos + 2)) in | |
| Array.set codes (at (pos + 3)) (f v1 v2); | |
| (codes, pos) | |
| let rec run_program (program : program) : int = | |
| match current_opcode program with | |
| | Add -> execute program (+) |> continue | |
| | Multiply -> execute program ( * ) |> continue | |
| | Halt -> final_result program | |
| and continue (codes, pos) = run_program (codes, pos + 4) | |
| let fix_1202_alarm codes = | |
| Array.set codes 1 12; | |
| Array.set codes 2 2; | |
| codes | |
| let () = | |
| let source_code = | |
| In_channel.input_line_exn In_channel.stdin | |
| |> String.split_on_chars ~on:[','] | |
| |> List.map ~f:Int.of_string | |
| |> Array.of_list in | |
| let result = | |
| run_program (fix_1202_alarm source_code, 0) in | |
| printf "%d\n" result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment