From: Heesob Park Date: 2008-11-06T23:54:16+09:00 Subject: Re: Combination of numbers in an array that add up to x 2008/11/5 Hae Lee : > 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? If you really want one-liner and the solution exists, try this: a = [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] t = 3435.78 ((s||={})[(a=a.sort_by{rand} while s[a])||a]=1 while(r=(1..a.size).map{|x|a[0,x]}.find{|y|y.inject{|z,n|z+n}==t}).nil?)||r Regards, Park Heesob