changeset 68:cd6e3d6c1338

Day 13: some refactoring
author Lewin Bormann <lbo@spheniscida.de>
date Sat, 23 Dec 2023 21:39:38 +0100
parents b4d590e70ccd
children 64fc8f99bddd
files 2023/day13.ml
diffstat 1 files changed, 17 insertions(+), 25 deletions(-) [+]
line wrap: on
line diff
--- a/2023/day13.ml	Sat Dec 23 21:36:45 2023 +0100
+++ b/2023/day13.ml	Sat Dec 23 21:39:38 2023 +0100
@@ -34,41 +34,33 @@
 end
 
 module Part1 = struct
-  (* check if mirror axis exists between columns c and c+1 (one-based) *)
-  let check_mirror_v field c =
-    let rec check_with_off field c off =
-      if c - off - 1 < 0 || c + off >= field.cols then
-        off > 0 && off < field.cols
+  let check_mirror getter max field ix =
+    let rec check_with_off field ix off =
+      if ix - off - 1 < 0 || ix + off >= max then off > 0 && off < max
       else
-        let left = get_column field (c - off - 1)
-        and right = get_column field (c + off) in
-        Array.equal equal_tile left right && check_with_off field c (off + 1)
+        let left = getter field (ix - off - 1)
+        and right = getter field (ix + off) in
+        Array.equal equal_tile left right && check_with_off field ix (off + 1)
     in
-    check_with_off field c 0
+    check_with_off field ix 0
+
+  (* check if mirror axis exists between columns c and c+1 (one-based) *)
+  let check_mirror_v field c = check_mirror get_column field.cols field c
 
   (* check if mirror axis exists between rows r and r+1 (one-based) *)
-  let check_mirror_h field r =
-    let rec check_with_off field r off =
-      if r - off - 1 < 0 || r + off >= field.rows then
-        off > 0 && off < field.rows
-      else
-        let top = get_row field (r - off - 1)
-        and bottom = get_row field (r + off) in
-        Array.equal equal_tile top bottom && check_with_off field r (off + 1)
-    in
-    check_with_off field r 0
+  let check_mirror_h field r = check_mirror get_row field.rows field r
+
+  let check_any checker max field =
+    let indices = List.range 1 (max + 1) in
+    List.find indices ~f:(fun ix -> checker field ix)
 
   (* check if mirror axis exists between any rows r and r+1 (one-based),
      and return r. *)
-  let check_any_h field =
-    let rows = List.range 1 (field.rows + 1) in
-    List.find rows ~f:(fun r -> check_mirror_h field r)
+  let check_any_h field = check_any check_mirror_h field.rows field
 
   (* check if mirror axis exists between any columns c and c+1 (one-based),
      and return c. *)
-  let check_any_v field =
-    let cols = List.range 1 (field.cols + 1) in
-    List.find cols ~f:(fun c -> check_mirror_v field c)
+  let check_any_v field = check_any check_mirror_v field.cols field
 
   (* a symmetry may be either horizontal or vertical or both.
      The integer signifies the row/column to the left/top of the