From faa6186c4332ea118e18df75fc839e6de8bb8275 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Wed, 11 Jan 2023 21:34:33 +0100 Subject: [PATCH] Day 2 part 1 --- ocaml/2.ml | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 ocaml/2.ml diff --git a/ocaml/2.ml b/ocaml/2.ml new file mode 100644 index 0000000..0de17a1 --- /dev/null +++ b/ocaml/2.ml @@ -0,0 +1,49 @@ +#use "lib/file_utils.ml" ;; + +type shape = Rock | Paper | Scissors +type outcome = Win | Tie | Loss + +let shape_of = function + | 'A' | 'X' -> Rock + | 'B' | 'Y' -> Paper + | 'C' | 'Z' -> Scissors + | s -> failwith ("invalid shape: " ^ (String.make 1 s)) +;; + +let score_of_shape = function + | Rock -> 1 + | Paper -> 2 + | Scissors -> 3 +;; + +let score_of_outcome = function + | Loss -> 0 + | Tie -> 3 + | Win -> 6 +;; + +let outcome_of = function + | Rock, Scissors -> Win + | Paper, Rock -> Win + | Scissors, Paper -> Win + | a, b when a = b -> Tie + | _ -> Loss +;; + +let play_round line = + let op_move = shape_of (String.get line 0) in + let my_move = shape_of (String.get line 2) in + let outcome = outcome_of(my_move, op_move) in + let outcome_score = score_of_outcome outcome in + let shape_score = score_of_shape my_move in + outcome_score + shape_score +;; + +let contents = read_file "inputs/2.txt" in +let score = String.split_on_char '\n' contents + |> List.filter (fun l -> String.trim l <> "") + |> List.map play_round + |> List.fold_left (+) 0 +in + +Printf.printf "%d" score