-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday08.ml
50 lines (41 loc) · 1.33 KB
/
day08.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module Regs = CCMap.Make(String)
type instruction = {
reg : string;
instr : string;
condReg : string;
condOp : string;
amount : int;
value : int;
}
let parse_operator = function
| "<" -> ( < )
| ">" -> ( > )
| "<=" -> ( <= )
| ">=" -> ( >= )
| "==" -> ( = )
| "!=" -> ( <> )
| _ -> failwith "invalid operator"
let make_instruction line =
let a = line |> String.split_on_char ' ' |> Array.of_list in
{ reg = a.(0); instr = a.(1); amount = int_of_string a.(2);
condReg = a.(4); condOp = a.(5); value = int_of_string a.(6) }
let execute (regs, max) line =
let get_reg_val key = Regs.get_or key regs ~default:0 in
let regVal = get_reg_val line.condReg in
let ( <?> ) = parse_operator line.condOp in
if regVal <?> line.value then
let v = get_reg_val line.reg in
let ( +- ) = if line.instr = "inc" then (+) else (-) in
let nv = v +- line.amount in
let regs' = Regs.add line.reg nv regs in
let max' = if nv > max then nv else max in
(regs', max')
else (regs, max)
let parse filename =
List.map make_instruction CCIO.(with_in filename read_lines_l)
let r, m =
parse "inputs/08.txt" |> List.fold_left execute (Regs.empty, 0)
let find_largest r =
Regs.fold (fun _ v a -> if v > a then v else a) r 0
let part_1 = Printf.printf "%d\n" (find_largest r)
let part_2 = Printf.printf "%d\n" m