diff --git a/lib/day2/day2.ex b/lib/day2/day2.ex index 2d4597c..9c12c9f 100644 --- a/lib/day2/day2.ex +++ b/lib/day2/day2.ex @@ -15,4 +15,41 @@ defmodule Day2 do |> String.split(";") |> Enum.map(&String.trim/1) end + + def parse_game_set_amounts(set_string) do + initial_cube_map = %{ + :red => 0, + :green => 0, + :blue => 0 + } + + cube_list = String.split(set_string, ",") + + Enum.reduce(cube_list, initial_cube_map, fn x, acc -> + case String.contains?(x, "red") do + true -> Map.put(acc, :red, extract_integer(x)) + false -> acc + end + |> (fn acc -> + case String.contains?(x, "green") do + true -> Map.put(acc, :green, extract_integer(x)) + false -> acc + end + end).() + |> (fn acc -> + case String.contains?(x, "blue") do + true -> Map.put(acc, :blue, extract_integer(x)) + false -> acc + end + end).() + end) + end + + def remove_non_digits(str) do + Regex.replace(~r/\D/, str, "") + end + + def extract_integer(string) do + remove_non_digits(string) |> String.to_integer() + end end diff --git a/test/day1/day1_test.exs b/test/day1/day1_test.exs index d25ff77..60acfc6 100644 --- a/test/day1/day1_test.exs +++ b/test/day1/day1_test.exs @@ -38,16 +38,16 @@ defmodule Day1Test do 1, fn x -> Day1.convert_word_to_integer_string(x) end ) == [ - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" + "zero0zero", + "one1one", + "two2two", + "three3three", + "four4four", + "five5five", + "six6six", + "seven7seven", + "eight8eight", + "nine9nine" ] end @@ -59,7 +59,7 @@ defmodule Day1Test do assert Day1.convert_substrings_to_integer_strings( "zero one two three four five six seven eight nine" ) == - "0 1 2 3 4 5 6 7 8 9" + "zero0zero one1one two2two three3three four4four five5five six6six seven7seven eight8eight nine9nine" end test "should convert substrings according to a replacement map" do diff --git a/test/day2/day2_test.exs b/test/day2/day2_test.exs index c303aad..d638097 100644 --- a/test/day2/day2_test.exs +++ b/test/day2/day2_test.exs @@ -29,12 +29,16 @@ defmodule Day2Test do end test "it parses a game set to produce a map of red, green and blue amounts" do - set_string = "7 red, 14 blue 8 green" + set_string = "7 red, 14 blue, 8 green" - assert Day2.get_game_set_amounts(set_string) = %{ + assert Day2.parse_game_set_amounts(set_string) == %{ :red => 7, :green => 8, :blue => 14 } end + + test "it extracts integer from a string" do + assert Day2.extract_integer("21 meow 21") == 2121 + end end