Make 2402 part 2 more idiomatic.

This commit is contained in:
2024-12-04 16:28:58 +00:00
parent 003fac75d6
commit 4d6a0683bf

View File

@@ -1,4 +1,6 @@
let search_string big little =
(** [occurances big little] counts the number of occurances of the string
[little] in [big]. *)
let occurances big little =
let re = Str.regexp_string little in
let rec impl acc pos =
try
@@ -8,6 +10,8 @@ let search_string big little =
in
impl 0 0
(** [is_inbounds sa (x, y)] returns true if (x, y) is a valid location in the
array of strings [sa]. *)
let is_inbounds sa (x, y) =
y >= 0 && y < Array.length sa && x >= 0 && x < String.length sa.(y)
@@ -26,7 +30,7 @@ let gen_strings sa (x, y) (dx, dy) (dx2, d2y) =
impl (s :: acc) (x + dx2) (y + d2y)
else acc
in
List.rev (impl [] x y)
impl [] x y
let gen_search_strings sa =
let right = String.length sa.(0) - 1 in
@@ -36,12 +40,11 @@ let gen_search_strings sa =
@ gen_strings sa (0, 1) (1, 1) (0, 1)
@ gen_strings sa (right, 0) (-1, 1) (-1, 0)
@ gen_strings sa (right, 1) (-1, 1) (0, 1)
@ []
let find_xmas sa =
let search_strings = gen_search_strings sa in
List.fold_left (fun acc x -> acc + search_string x "XMAS") 0 search_strings
+ List.fold_left (fun acc x -> acc + search_string x "SAMX") 0 search_strings
List.fold_left (fun acc x -> acc + occurances x "XMAS") 0 search_strings
+ List.fold_left (fun acc x -> acc + occurances x "SAMX") 0 search_strings
let find_mas sa x y =
let find_ms a b c d =
@@ -55,13 +58,16 @@ let find_mas sa x y =
|| find_ms 'M' 'S' 'M' 'S' || find_ms 'S' 'M' 'S' 'M')
let find_mases sa =
let acc = ref 0 in
for y = 1 to Array.length sa - 2 do
for x = 1 to String.length sa.(y) - 2 do
if find_mas sa x y then acc := !acc + 1
done
done;
!acc
let rec col_check acc x y =
if x >= String.length sa.(y) - 1 then acc
else if find_mas sa x y then col_check (acc + 1) (x + 1) y
else col_check acc (x + 1) y
in
let rec row_check acc y =
if y >= Array.length sa - 1 then acc
else row_check (col_check acc 1 y) (y + 1)
in
row_check 0 1
let sa_of_file fname = Aoc.strings_of_file fname |> Array.of_list