From: Giampiero Zanchi Date: 2008-11-05T22:29:22+09:00 Subject: Re: Combination of numbers in an array that add up to x Hae Lee wrote: > Objective: Find list of values in an array that adds up to a specific > sum. > - > I have a list of values in an array: > [2429.63, 497.87, 51.96, 59.43, 138.4, 66.22, 28.74, 1.75, 2075.13, > 556.14, 112.56, 116.5, 84.41, 55.97, 139.07, 24.46] > > I want to find a combination among these numbers that adds up to a total > sum of: > 3435.78 > > I was hoping a one-liner in irb would do the trick but I haven't found a > method, etc. that will help me do this. Thoughts regarding? Hi from Italy, this is my first post on this forum; I am a ruby beginner, so I took your question as an exercise; the following is the one solution I found (integer values): 175, 11256, 11650, 13840, 13907, 49787, 242963 v = [2429.63, 497.87, 51.96, 59.43, 138.4, 66.22, 28.74, 1.75, 2075.13, 556.14, 112.56, 116.5, 84.41, 55.97, 139.07, 24.46] goal = 343578 v.map! {|x| (x*100).to_i} v.sort! def to_binary(i) bin_vett = [] loop do bin_vett.push(i % 2) i = i / 2 break if i == 0 end bin_vett.reverse end n = 2 ** v.size n.times do |i| b = to_binary(i) sum = 0 b.each_index do |j| sum += v[j] if b[j] == 1 end if sum == goal then b.each_index do |j| print "#{v[j]} " if b[j] == 1 end end end -- Posted via http://www.ruby-forum.com/.