From 0f34d9a931791406d2cabf282742530195f71927 Mon Sep 17 00:00:00 2001 From: DJ O'Leary Date: Mon, 8 Dec 2025 01:55:28 +0100 Subject: refactor(2025,ocaml): use result type for answers to allow for returning errors --- 2025/ocaml/lib/application/d04p01.ml | 46 ++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 20 deletions(-) (limited to '2025/ocaml/lib/application/d04p01.ml') diff --git a/2025/ocaml/lib/application/d04p01.ml b/2025/ocaml/lib/application/d04p01.ml index 260c9e9..7c69de4 100644 --- a/2025/ocaml/lib/application/d04p01.ml +++ b/2025/ocaml/lib/application/d04p01.ml @@ -1,26 +1,32 @@ open Domain +let err_empty_input = "input is empty" + let rec solve input () = - let matrix = Matrix.M.of_string input in - let count_paper lst = List.length @@ List.filter (fun c -> c <> ".") lst in - let accessible_rolls_of_paper = ref 0 in - for y = 0 to Array.length matrix - 1 do - for x = 0 to Array.length matrix.(y) - 1 do - if matrix.(y).(x) = "." then () - else - let neighbour_coords = Matrix.M.get_valid_neighbours matrix x y in - let neighbours = - List.map (fun (x', y') -> Matrix.M.get matrix x' y') neighbour_coords - in - let paper_count = count_paper neighbours in - let is_accessible = paper_count < 4 in - if is_accessible then - accessible_rolls_of_paper := !accessible_rolls_of_paper + 1 ; - print_iteration_debug_msg x y neighbour_coords neighbours paper_count - is_accessible - done - done ; - !accessible_rolls_of_paper + if input = "" then Error err_empty_input + else + let matrix = Matrix.M.of_string input in + let count_paper lst = List.length @@ List.filter (fun c -> c <> ".") lst in + let accessible_rolls_of_paper = ref 0 in + for y = 0 to Array.length matrix - 1 do + for x = 0 to Array.length matrix.(y) - 1 do + if matrix.(y).(x) = "." then () + else + let neighbour_coords = Matrix.M.get_valid_neighbours matrix x y in + let neighbours = + List.map + (fun (x', y') -> Matrix.M.get matrix x' y') + neighbour_coords + in + let paper_count = count_paper neighbours in + let is_accessible = paper_count < 4 in + if is_accessible then + accessible_rolls_of_paper := !accessible_rolls_of_paper + 1 ; + print_iteration_debug_msg x y neighbour_coords neighbours paper_count + is_accessible + done + done ; + Ok !accessible_rolls_of_paper and print_iteration_debug_msg x y neighbour_coords neighbours paper_count is_accessible = -- cgit v1.2.3