Skip to content

Commit

Permalink
pass test for it parses a game set to produce a map of red, green and…
Browse files Browse the repository at this point in the history
… blue amounts
  • Loading branch information
samjowen committed Dec 27, 2023
1 parent 770a693 commit 1548c62
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 13 deletions.
37 changes: 37 additions & 0 deletions lib/day2/day2.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
22 changes: 11 additions & 11 deletions test/day1/day1_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
8 changes: 6 additions & 2 deletions test/day2/day2_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 1548c62

Please sign in to comment.