diff --git a/bin/day2423.ml b/bin/day2423.ml index 6bfec85..68eb174 100644 --- a/bin/day2423.ml +++ b/bin/day2423.ml @@ -20,25 +20,24 @@ let load_file fname = |> List.map make_pairs |> List.fold_left add_connection StringMap.empty -let rec find_second_member acc connections visited a = - let rec impl acc a b = function +let rec find_second_member acc connections visited a candidates = + let rec impl acc set = function | [] -> acc - | c :: t -> impl (StringSet.of_list [ a; b; c ] :: acc) a b t + | c :: t -> impl (StringSet.add c set :: acc) set t in - function - | [] -> acc - | h :: t -> + match StringSet.choose_opt candidates with + | None -> acc + | Some h -> + let candidates = StringSet.remove h candidates in if StringSet.mem h visited then - find_second_member acc connections visited a t + find_second_member acc connections visited a candidates else let visited = StringSet.add h visited in - let anh = - StringSet.inter - (StringMap.find a connections) - (StringMap.find h connections) + let anh = StringSet.inter (StringMap.find h connections) candidates in + let acc = + impl acc (StringSet.of_list [ a; h ]) (StringSet.to_list anh) in - let acc = impl acc a h (StringSet.to_list anh) in - find_second_member acc connections visited a t + find_second_member acc connections visited a candidates let rec find_rings acc visited connections = function | [] -> acc @@ -48,7 +47,7 @@ let rec find_rings acc visited connections = function let visited = StringSet.add h visited in let acc = find_second_member acc connections visited h - (StringSet.to_list (StringMap.find h connections)) + (StringMap.find h connections) in find_rings acc visited connections t @@ -56,14 +55,11 @@ let rec find_rings acc visited connections = function letter ['t']. *) let starts_with_t set = StringSet.exists (fun x -> x.[0] = 't') set -let set_compare a b = compare (StringSet.elements a) (StringSet.elements b) - let part1 connections = StringMap.to_list connections |> List.map fst |> find_rings [] StringSet.empty connections - |> List.filter starts_with_t |> List.sort_uniq set_compare |> List.length - |> string_of_int + |> List.filter starts_with_t |> List.length |> string_of_int (** [search_candidate max_lst connections current candidates] searches for the longest star network that contains all the computers in [current] and maybe