We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 31
Hacker Rank 07 - Valid Colors
Published on: 2025-06-01
Tags:
elixir, Side Project, Hacker Rank
For this challenge I needed to parse strings with different "colored balls" that are represented as RBGY In this case there are 4 things to check: There are as many red balls as green balls. There are as many yellow balls as blue balls. Difference between the number of red balls and green balls in every prefix of the sequence is at most Difference between the number of yellow balls and blue balls in every prefix of the sequence is at most 1. For this case I wanted to use some recursion as well as some basic Enums. I was able to create the map with all the colors as well as check for the prefix within the same function. defp get_count(string) do count_prefix_loop(string, %{B: 0, G: 0, R: 0, Y: 0}) end defp count_prefix_loop([], map), do: map defp count_prefix_loop([head | tail], map) do map = Map.update(map, String.to_atom(head), 1, fn value -> value + 1 end) if not prefix_check?(map) do false else count_prefix_loop(tail, map) end end The first line is the helper function so that I can pass only what is needed to the loop and I can run a set of pipes on the outer layer of the code. The next line is the base-case for the loop, it will return the map and that is it once it gets to the end of the word. The last one has some basic logic for the loop as well as the prefix_check?. Assuming that we don't have an issue with the prefix it will simply go through the string and update the map with the count of each "ball" Let's take a second to talk about the prefix check as it helps us avoid going through every character of a word. defp prefix_check?(map), do: prefix_RG?(map) and prefix_YB?(map) defp prefix_RG?(map), do: abs(map[:R] - map[:G]) <= 1 defp prefix_YB?(map), do: abs(map[:Y] - map[:B]) <= 1 This is part of the loop that will be run for every letter of the string, with the exception of it not passing the prefix test. The test is simple if at any point in the update of the map It fails either of the prefix conditions it will escape the loop. This helps to be sure that failures don't got though the rest of the loop. As with the rest of the problems I'll leave the read and the display up to the reader.