We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 30
Hacker Rank 06 - Combinations of powers that equal Number
Published on: 2025-05-31
Tags:
elixir, Blog, Side Project, Hacker Rank
So for this one we are given a number and a power, we are then to find the number of ways that we can get the number for adding any combination of numbers to the power. input 10 2 10 = 1^2 + 3^2 = 1 + 9 So for this I new that I needed to find the largest integer that is <= the given number and get a list of all the numbers that are less than or equal to that integer def set_of_integers([number, power]) do max_base = trunc(:math.pow(number, 1.0 / power)) Enum.map(1..max_base, fn i -> round(:math.pow(i, power)) end) end So I find the value that is equal to the root (base power) and then create list of all the numbers up to that point. (I save a step for later here and make the list have the integer^power because we need that later anyway). Next we need to find the combinations of those numbers that are equal to the number given, Recursion to the rescue. def count_ways([], 0), do: 1 #base case for a list that sums to the number. (1) def count_ways([], _), do: 0 #base case for a list that doesn't sum to the number. (2) def count_ways([h | t], target) when h > target, do: count_ways(t, target) # case for when the sum of the list so far exceeds the target. (3) def count_ways([h | t], target) do # Include h or exclude h count_ways(t, target - h) + count_ways(t, target) # Recursion loop end end Okay so lets go over this. Also see the # comments above. h stands for the head of the list, t stands for the tail. we are trying to do all combinations of the list. So looking at the list we are taking values from the list and subtracting from the target. If it goes above the target (3) it just moves on to an other test, if it doesn't equal the target (2) it will return nothing, if it equals the target (after computing the entire combination) it will return 1. Now lets go over the actual logic for the recursion. If you look at the recursion loop you see that we remove an integer from the target and test the rest of the set, OR forget h and test the rest of the set. In this case we will go through every combination if and only if there is a chance of summing to the target.
