We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 34
Hacker Rank 08 - Super Number
Published on: 2025-06-03
Tags:
elixir, Blog, Testing, Hacker Rank
For this challenge we are given 2 integers one is the number and the other is the amount of repeats. We are to take those numbers and create a single number that will be the basis for the SUPER NUMBER loop. Its works like this if the SUPER NUMBER is a single digit you are done, but if it has more than 1 digit you must sum the digits and then test again. input: 148 3 super_digit(P) = super_digit(148148148) = super_digit(1+4+8+1+4+8+1+4+8) = super_digit(39) = super_digit(3+9) = super_digit(12) = super_digit(1+2) = super_digit(3) = 3. Output: 3 So for this problem there was a few things that I wanted to get out of the way. First is processing the input. Ill include it here as the time they gave us for this is a lot less than a normal problem, and every second counts. def read do IO.read(:stdio, :all) |> String.split(" ") |> Enum.map(&String.to_integer(&1)) |> parse_input() end def parse_input([number, times]) do [Integer.digits(number), times] end I would normally just send the last line to an other Enum but in this case it makes more sense to just send it to a parse. Next we want to set the first SUPER NUMBER def set_super_number([number_digits, times]) do Enum.sum(number_digits) * times |> Integer.digits() end This is the only time we are able to use this logic as after we set the first SUPER NUMBER we will have no way of knowing if there is any repeats. This does reduce the amount of steps by (times - 1 * length of the number) so there is a little optimization here. def loop([number]) when is_integer(number), do: number def loop(number_list) do number_list # this makes sure that each step is done then passed to the next. |> Enum.sum() |> Integer.digits() |> loop() end This is the loop and I wanted to be sure that tail recursion is used. So I had to set the number_list. This is a simple recursion so it doesn't take too long to run. the base case works as if it was a set of numbers the inside would not evaluate to true for the guard. As only a solo integer could work in that case.
