From: SonOfLilit Date: 2007-07-15T17:52:03+09:00 Subject: Re: xkcd and ugly code Here's a bit of DRYing up of your code, which isn't a good idea - as David mentioned, there are better ways to do this. Note: untested. menu= [2.15, 2.75, 3.35, 3.55, 4.20, 5.80] target= 15.05 def r(state, menu, target) # state is an array of indexes. returns nil unless a solution was found i = state.length if i < menu.length 0.upto(target/menu[i].to_i) do |a| state.shift(a) retval = r(state, menu, target) state.unshift return retval if retval end else total = (0..i-1).inject{0) {|index, m| m += state[index]*menu[i - index] if (total - target).abs<0.01 then return state end return nil end end total = 0.0 # this line is twisted, but I really enjoyed writing it. so it stays. this isn't production code anyway. and you'll have to implement collect_with_index, I think. print r([], menu, target). collect_with_index{|amount, i| total += amount*menu[i]; "#{amount} * $#{menu[i]}" }. push("------ #{total}").join("\n")