aoc2020/day3.ml

43 lines
1,003 B
OCaml
Raw Normal View History

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