Compare commits

...

3 Commits

2 changed files with 24 additions and 14 deletions

View File

@@ -1,19 +1,16 @@
module IntSet = Set.Make (Int) module IntSet = Set.Make (Int)
module IntMap = Map.Make (Int)
(** [add_rule a b m] adds the rule that [a] must appear before [b] to the rule (** [add_rule a b m] adds the rule that [a] must appear before [b] to the rule
map [m]. *) map [m]. Returns the updated map [m] *)
let add_rule a b = let add_rule a b m =
let update_rule = function match Hashtbl.find_opt m a with
| None -> Some (IntSet.singleton b) | None -> Hashtbl.add m a (IntSet.singleton b)
| Some s -> Some (IntSet.add b s) | Some s -> Hashtbl.replace m a (IntSet.add b s)
in
IntMap.update a update_rule
(** [find_rule a b m] returns [true] if the rule map [m] says that [a] should (** [find_rule a b m] returns [true] if the rule map [m] says that [a] should
appear before [b]. *) appear before [b]. *)
let find_rule a b m = let find_rule a b m =
match IntMap.find_opt a m with match Hashtbl.find_opt m a with
| Some s -> ( match IntSet.find_opt b s with Some _ -> true | None -> false) | Some s -> ( match IntSet.find_opt b s with Some _ -> true | None -> false)
| None -> false | None -> false
@@ -43,15 +40,18 @@ let rec is_page_order_valid m pages =
[tail] starts the line after the empty line. *) [tail] starts the line after the empty line. *)
let parse_rules = let parse_rules =
let re = Str.regexp_string "|" in let re = Str.regexp_string "|" in
let rec impl acc = function let m = Hashtbl.create 17 in
| "" :: t -> (acc, t) let rec impl = function
| "" :: t -> (m, t)
| [] -> failwith "parse_rules.impl" | [] -> failwith "parse_rules.impl"
| h :: t -> ( | h :: t -> (
match List.map int_of_string (Str.split re h) with match List.map int_of_string (Str.split re h) with
| [ a; b ] -> impl (add_rule a b acc) t | [ a; b ] ->
add_rule a b m;
impl t
| _ -> failwith "parse_rules.impl") | _ -> failwith "parse_rules.impl")
in in
impl IntMap.empty impl
(** [parse_page_orders lst] parses a list of page orders. *) (** [parse_page_orders lst] parses a list of page orders. *)
let parse_page_orders = let parse_page_orders =

View File

@@ -20,7 +20,17 @@
(synopsis "Implementation of AoC competitions in OCaml") (synopsis "Implementation of AoC competitions in OCaml")
(description (description
"Implementation of solutions to various Advent of Code exercises written in OCaml") "Implementation of solutions to various Advent of Code exercises written in OCaml")
(depends ocaml dune) (depends
(ocaml
(>= 5.2))
dune
(ocamlformat
(and
:dev
(= 0.26.2)))
(odoc :build)
(utop :dev)
(ocaml-lsp-server :dev))
(tags (tags
(advent-of-code ocaml))) (advent-of-code ocaml)))