Moved Grid to Aoc module.
This commit is contained in:
36
lib/aoc.ml
36
lib/aoc.ml
@@ -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
|
||||
|
Reference in New Issue
Block a user