From: swille Date: 2005-10-23T10:52:25+09:00 Subject: Re: combination sums of several arrays On 10/22/05, David Vincelli wrote: > I'm writing a little BlackJack program for fun and I'm at the point > where I have to decide which point value to assign to a hand. As you > know, an Ace may be worth 1 or 11 in this game - whatever is closer to > 21 without going over. > > Considering this, I know I have to come up with an algorithm that > first determines what the different point values may be (the extreme > case may be that a player got all four aces, now I'd have to determine > all combinations of the players cards). > > This demonstrates some of the code I wrote: > > pl = Player.new > pl.hand.each { |card| p pl.card.value } > > might produce this output: > [1, 11] > [5] > [10] > > For the above example, so what I'm looking for is a method that will > calculate all possible point totals. For this example I'd get the > results [16, 26] > > I'm thinking I might do this by first building a binary tree, creating > unique branches that would add up to the results when I applied some > recursive algorithm to it. But I'm curious to know how other people > might do this? (I'm especially curious to see if anyone has some > solution that does not require building a tree and recursing..). > > Thanks, > > -- > David Vincelli > > Maybe I'm not understanding what exactly you want, but I think I'd dump the [1, 10] thing and just count it as [1]. Then maybe something like: sum = pl.hand.inject { |sum, n| sum + n } if pl.hand.include?(1) if sum + 10 <= 21 sum += 10 end end Or did I miss something?