solve day 10

This commit is contained in:
ryan committed 2023-10-07 12:58:57 -07:00
1 parent bf5d3c1656
commit c93c273ffd
4 files changed
+339 -1

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
open Containers
let parse_lines () =
let lines = Utils.lines_of_input 10 in
let _, state_history =
List.fold_flat_map
(fun (cycle, reg) instruction ->
match String.split ~by:" " instruction with
| [ "noop" ] -> (cycle + 1, reg), [ cycle + 1, reg ]
| [ "addx"; num ] ->
let num = int_of_string num in
(cycle + 2, reg + num), [ cycle + 1, reg; cycle + 2, reg ]
| _ -> failwith @@ Printf.sprintf "failed to parse '%s'" instruction)
(0, 1)
lines
in
state_history
;;
let part1 () =
let history = parse_lines () in
history
|> List.find_all (fun (cycle, _) ->
match cycle with
| 20 | 60 | 100 | 140 | 180 | 220 -> true
| _ -> false)
|> List.fold_left (fun acc (cycle, reg) -> acc + (cycle * reg)) 0
;;
let part2 () =
let screen_width = 40 in
let history = parse_lines () in
history
|> List.map (fun (cycle, reg) ->
let column = Int.(cycle mod screen_width) in
let sprite_dist = abs @@ (reg + 1 - column) in
if sprite_dist <= 1 then '#' else ' ')
|> List.chunks 40
|> List.map String.of_list
|> List.iter Fun.(print_string %> print_newline)
;;
let print () =
Printf.(
printf "Day 10.1: %d\n" @@ part1 ();
printf "Day 10.2:\n";
part2 ())
;;