summaryrefslogtreecommitdiffstats
path: root/lib/day07.ml
blob: 56de6496f3f423faf05b07285292a191c09e8d85 (plain) (blame)
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
(*
 * SPDX-FileCopyrightText: Copyright 2025 Alexandre Jesus <https://adbjesus.com>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *)

let solve transition_fn answer_fn ch =
  (* the following assumes tachyon splitters are not adjacent *)
  (* it also assume that the input is a perfect grid *)
  let lines = In_channel.input_lines ch in
  let start = String.index (List.hd lines) 'S' in
  let m = String.length (List.hd lines) in
  let cur = Array.make m 0 in
  cur.(start) <- 1;
  List.iter (String.iteri (transition_fn cur)) (List.tl lines);
  Printf.printf "%d\n" (answer_fn cur)

let part1 ch =
  let ans = ref 0 in
  let transition_fn cur j c =
    if c = '^' then (
      cur.(j - 1) <- Int.logor cur.(j - 1) cur.(j);
      cur.(j + 1) <- Int.logor cur.(j + 1) cur.(j);
      ans := !ans + cur.(j);
      cur.(j) <- 0)
  in
  let answer_fn _cur = !ans in
  solve transition_fn answer_fn ch

let part2 ch =
  let transition_fn cur j c =
    if c = '^' then (
      cur.(j - 1) <- cur.(j - 1) + cur.(j);
      cur.(j + 1) <- cur.(j + 1) + cur.(j);
      cur.(j) <- 0)
  in
  let answer_fn cur = Array.fold_left ( + ) 0 cur in
  solve transition_fn answer_fn ch