Advent of Code 2024 - Day 25Code Chronicle

OCaml | Problem statement | Source code | Tags:

IDK, this feels like a day 3 problem. I parse each lock and key to a list of integers saying how many #s are in each column.

let count_col rows =
let a = Array.of_list rows in
let n = Array.length a in
let m = String.length (List.hd rows) in
let counts = Array.make m 0 in
for i = 0 to n - 1 do
let s = a.(i) in
for j = 0 to m - 1 do
if s.[j] = '#' then counts.(j) <- counts.(j) + 1
done
done;
Array.to_list counts
ocaml

I can tell if a schematic is a key or a lock by testing if the first character is #, since locks have all #s in the first row while keys have all .s.

Finally I just found how many lock-key combinations match with List.for_all2 (fun k l -> k + l <= 7) key lock:

let total =
List.fold_left
(fun acc key ->
List.fold_left
(fun acc lock ->
if List.for_all2 (fun k l -> k + l <= 7) key lock then acc + 1
else acc)
acc locks)
0 keys
ocaml