Moved Grid to Aoc module.

This commit is contained in:
2024-12-10 11:31:02 +00:00
parent 76dc338c9a
commit fe93f65f6a
2 changed files with 82 additions and 1 deletions

View File

@@ -21,7 +21,10 @@ let main prep parts =
Printf.printf "Usage: %s <fname>\n" Sys.executable_name;
exit 2
with e ->
Printf.printf "An error occured: %s\n" (Printexc.to_string e);
Printf.fprintf stderr "An error occured: %s\n" (Printexc.to_string e);
if Printexc.backtrace_status () then (
Printf.fprintf stderr "Backtrace:\n";
Printexc.print_backtrace stderr);
exit 1
module IntPair = struct
@@ -32,3 +35,34 @@ module IntPair = struct
end
module IntPairSet = Set.Make (IntPair)
module Grid = struct
type t = { grid : string; width : int; height : int }
let of_file fname =
let strs = strings_of_file fname in
let width = String.length (List.hd strs) in
let grid = List.fold_left ( ^ ) "" strs in
let height = String.length grid / width in
{ grid; width; height }
let length grid = String.length grid.grid
let pos_of_idx grid idx = (idx mod grid.width, idx / grid.width)
let idx_of_pos grid (x, y) = x + (y * grid.width)
let get_by_idx grid idx = grid.grid.[idx]
let get_by_pos grid pos = get_by_idx grid (idx_of_pos grid pos)
let pos_is_valid grid (x, y) =
x >= 0 && x < grid.width && y >= 0 && y < grid.height
let idx_from_opt grid = String.index_from_opt grid.grid
let update_pos grid pos c =
let idx = idx_of_pos grid pos in
let builder = Buffer.create (length grid) in
Buffer.add_string builder (String.sub grid.grid 0 idx);
Buffer.add_char builder c;
Buffer.add_string builder
(String.sub grid.grid (idx + 1) (length grid - idx - 1));
{ grid with grid = Buffer.contents builder }
end