I need to create a combination of sum of values closest to the target value. The combination needs to be of x numbers, where x is defined by the user. The algorithm will output the combination closest to a target value entered by the user. I also need to display the keys (values) that the algorithm returns.
Here is how I think the algorithm will work:
Target: 575
Values with corresponding keys:
150 [0] | 75 [1] | 123 [2] | 212 [3] | 23 [4] | 89 [5] | 20 [6]
77 [7] | 39 [8] | 16 [9] | 347 [10] | 512 [11] | 175 [12]
User wants Groups of: 5 values
The algorithm now runs combinations of sum of 5 values on the whole set and returns a sum of the values closest to the target value of 575
.
Result
150 [0] + 212 [3] + 23 [4] + 77 [7] + 89 [5] = 551
Keys used were 0, 3, 4, 7, and 5.
I could use Arrays#combination(n)
, but I will not be able to keep track of the keys. I have been able to come up with a Hash which stores "key" => "int values", but I have no idea how to come up with an optimized algorithm to combine values stored in a Hash.
{0=>"150"}
{1=>"212"}
{2=>"23"}
{3=>"77"}
{4=>"89"}
P.S. This is not a homework. Its a personal project to put on the resume, talk about at interviews, and to learn to convert my ideas to code.