From: Hae Lee Date: 2008-11-05T23:57:19+09:00 Subject: Re: Combination of numbers in an array that add up to x Giampiero Zanchi wrote: > 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 Hi there! Question: Are you sure you're a beginner? =) From a true beginner's perspective, your code looks advanced! Thanks so much!!! When I first started trying this on my own yesterday, I'd gotten as far as the first line in your code where I'd assigned the values in an array. If you get a chance, can you advise regarding the sources that you learned from to be able to put together something like the code you provided? The materials I'm using aren't as helpful apparently! =( Thanks again!!! -- Posted via http://www.ruby-forum.com/.