aoc2020/day3.ml

43 lines
1003 B
OCaml

type map = string array
let (.%[]) str i = str.[i mod String.length str]
let (+=) r x = r := !r + x
let iter_map ?(step_x=1) ?(step_y=1) f arr =
let i = ref 0 in let j = ref 0 in
while !i < Array.length arr do
f arr.(!i).%[!j];
i += step_x; j += step_y
done
let read_file = Bracket.infile_lines ~line:Fun.id ~of_seq:Array.of_seq
let count_trees ?step_x ?step_y map =
let count = ref 0 in
iter_map ?step_x ?step_y (fun c -> if c = '#' then incr count) map;
!count
let main1 input =
Format.printf "%d\n" (count_trees ~step_y:3 (read_file input))
let main2 input =
let map = read_file input in
Misc.print_prod
[count_trees map;
count_trees map ~step_y:3;
count_trees map ~step_y:5;
count_trees map ~step_y:7;
count_trees map ~step_x:2]
let main = Misc.main 3 [|main1; main2|]
let%expect_test _ =
main1 "../../data/day3";
[%expect{| 244 |}]
let%expect_test _ =
main2 "../../data/day3";
[%expect{| 90 * 244 * 97 * 92 * 48 = 9406609920 |}]