From: david karapetyan Date: 2007-07-15T17:23:45+09:00 Subject: Re: xkcd and ugly code ------=_Part_35648_13741577.1184487827268 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline This is basically a backtracking problem and the best way to deal with such problems I think is continuations. On 7/15/07, Sharon Phillips wrote: > > Hi, > > I read this xkcd strip the other day (http://www.xkcd.com/c287.html) > and, of course, had to solve it. So I whipped up a quick bit of Ruby > code that gave me the answers. Took about 5 minutes and then I was > happy. Except I wasn't, because I looked at what I'd written. Ugly > and not dry at all, sopping wet even; basically six nested loops. > I'll try to reproduce it below. > > Trouble is, I then spend the best part of an afternoon (don't tell my > boss ;-) trying to solve it elegantly, but couldn't. I did come up > with other ways that worked, but they were pretty cumbersome and slow. > > There has to be a 'ruby way' to do this. Any suggestions? > > Cheers, > Dave > > here's a rough approximation of the code I wrote: > > menu= [2.15, 2.75, 3.35, 3.55, 4.20, 5.80] > target= 15.05 > 0.upto(target/menu[0].to_i) do |a| > 0.upto(target/menu[1].to_i) do |b| > 0.upto(target/menu[2].to_i) do |c| > 0.upto(target/menu[3].to_i) do |d| > 0.upto(target/menu[4].to_i) do |e| > 0.upto(target/menu[5].to_i) do |f| > if ((total= a*menu[0] + > b*menu[1] + > c*menu[2] + > d*menu[3] + > e*menu[4] + > f*menu[5]) - target).abs<0.01 then > puts "\n#{a} * $#{menu[0]}" > puts "#{b} * $#{menu[1]}" > puts "#{c} * $#{menu[2]}" > puts "#{d} * $#{menu[3]}" > puts "#{e} * $#{menu[4]}" > puts "#{f} * $#{menu[5]}" > puts "---------------\n $#{total}" > end > end > end > end > end > end > end > > ------=_Part_35648_13741577.1184487827268--