As @pjs said, your question looks quite ambigious.
If you want to get a sum of array just use: array.reduce(0.0, &:+)
or even array.sum
.
If you want to get an array that will sum into given N
then you didnt give us sufficient details. What are limits? Can't you just do something like 4.5 -> [1, 1, 1, 1, 0.5]
?
upd
Author gave us a details. We have the array [5.0, 1.5, 0.5, 2, 1]
and by given number N
we should find a sum consisted of numbers from this array that equals N
. Basically it is like vending machine change problem (what coins should it give to customer).
You can google it just like that "vending machine change algorithm". For example: Java Algorithm to solve vendor machine 'change giving' problem
Here's my simple dynamic programming solution:
ALLOWED_NUMBERS = [5.0, 1.5, 0.5, 2, 1].sort.freeze
def into_sum_of_allowed_numbers(n)
return [] if n == 0
@cache ||= {}
return @cache[n] if @cache[n]
ALLOWED_NUMBERS.reverse_each do |x|
next if n - x < 0
lesser_sum = into_sum_of_allowed_numbers(n - x)
next unless lesser_sum
@cache[n] = lesser_sum + [x]
return @cache[n]
end
nil
end
into_sum_of_allowed_numbers(4.5) # ==> [0.5, 2, 2]
Basically, the idea is simple. With allowed numbers a, b, c
sum for number n
is [*sum_for(n - a), a]
or [*sum_for(n - c), c]
or [*sum_for(n - c), c]
.
You can do this without @cache
though it will be much slower.
I guess there're better solutions but recursive one looks most simple to me.