summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBrian Chu <brianmchu42@gmail.com>2022-08-21 16:41:02 -0700
committerBrian Chu <brianmchu42@gmail.com>2022-08-21 16:41:02 -0700
commit2e9342c1f28264d7ef609f0bb15a1c3792f7a352 (patch)
tree625ea9bc256fcead53b983ebfcf67aea526ef139
parentc9a6741617eb28834674a5ef84daae4366ac4101 (diff)
downloadAdventOfCode2018-main.tar.gz
solution day 2 main
-rw-r--r--bin/main.ml2
-rw-r--r--lib/day2.ml39
2 files changed, 38 insertions, 3 deletions
diff --git a/bin/main.ml b/bin/main.ml
index d72fbe4..b98bd05 100644
--- a/bin/main.ml
+++ b/bin/main.ml
@@ -22,6 +22,8 @@ let () =
     match (day, part) with
     | (1, 1) -> load_file "inputs/day1.txt" |> Day1.part_1 |> printf "%d\n"
     | (1, 2) -> load_file "inputs/day1.txt" |> Day1.part_2 |> printf "%d\n"
+    | (2, 1) -> load_file "inputs/day2.txt" |> Day2.part_1 |> printf "%d\n"
+    | (2, 2) -> load_file "inputs/day2.txt" |> Day2.part_2 |> printf "%s\n"
     | _ -> printf "invalid combination\n"
   
 
diff --git a/lib/day2.ml b/lib/day2.ml
index 7c5e310..8195678 100644
--- a/lib/day2.ml
+++ b/lib/day2.ml
@@ -1,7 +1,40 @@
+open Core
+
 (* Take text input from file and process accordingly *)
-let process_input _input = ()
+let process_input input = String.split_lines input |> Array.of_list
 
 (* Fill in solutions for each part *)
-let part_1 _input = ()
 
-let part_2 _input = ()
+let count_unique_chars word =
+  let counter = Hashtbl.create (module Char) in
+  let update_counter x =
+    Hashtbl.update counter x ~f:(function
+                                 | Some num -> succ num
+                                 | None -> 1) in
+  String.iter word ~f:update_counter;
+  counter
+
+let part_1 input = 
+  let ids = process_input input in
+  let counts = Array.map ids ~f:count_unique_chars in
+  let has_count hashtbl count =
+    Hashtbl.exists hashtbl ~f:(fun x -> count = x) in
+  let (count2, count3) =
+    Array.fold 
+      ~init:(0, 0) 
+      ~f:(fun (a, b) x -> ((if has_count x 2 then succ a else a), (if has_count x 3 then succ b else b)))
+      counts in
+  count2 * count3
+
+let string_diff string1 string2 =
+  String.foldi string1 ~init:[] ~f:(fun index accum ch -> if compare_char ch string2.[index] <> 0 then index::accum else accum)
+
+let part_2 input = 
+  let ids = process_input input in
+  let pairs = Array.cartesian_product ids ids
+              |> Array.filter ~f:(fun (a, b) -> compare_string a b <> 0)
+              |> Array.find ~f:(fun (a, b) -> string_diff a b |> List.length = 1)
+in
+match pairs with
+| Some (a, b) -> String.foldi a ~init:"" ~f:(fun index acc ch -> if compare_char ch b.[index] = 0 then String.concat [acc; String.make 1 ch] else acc)
+| None -> ""