Skip to content

Instantly share code, notes, and snippets.

@tokland
Created March 18, 2013 17:09
Show Gist options
  • Save tokland/5188902 to your computer and use it in GitHub Desktop.
Save tokland/5188902 to your computer and use it in GitHub Desktop.
# Or: require 'facets/enumerable/find_yield'
module Enumerable
def map_detect
self.each do |member|
if (result = yield(member))
return result
end
end
nil
end
end
class Array
# [:a, :b, :c, :d].merge(1 => :bb, 3 => :dd) #=> [:a, :bb, :c, :dd]
def merge_from_hash(hash)
map.with_index { |x, idx| hash.fetch(idx, x) }
end
end
class PitchersProblem
def initialize(total)
@total = total
end
def solve(current, final, solution = [])
if current == final
[solution + [current]]
else
(0...@total.size).to_a.permutation(2).map do |i1, i2|
free2 = @total[i2] - current[i2]
if current[i1] > 0 && free2 > 0
moved = [current[i1], free2].min
new_current = current.merge_from_hash({
i1 => current[i1] - moved,
i2 => current[i2] + moved,
})
if !solution.include?(new_current)
solve(new_current, final, solution + [current])
end
end
end.compact.flatten(1)
end
end
end
require 'pp'
problem = PitchersProblem.new([10, 7, 3])
p problem.solve([10, 0, 0], [5, 5, 0]).min_by(&:length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment