Created
February 15, 2023 20:37
-
-
Save michaelminter/734b0f5c4ea954515ead3c1534b46f35 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Given 2 water jugs of different sizes and an unlimited source of water, perform different operations to end up with some goal amount of water. | |
Write out the operations and how much water is in the jugs at each step. | |
Problem 1 --- Small = 3, Big = 5, Goal = 4 | |
- Start (0, 0) | |
- Fill small (3, 0) | |
- pour to big (0, 3) | |
- Fill small (3, 3) | |
- Pour from small to big (1, 5) | |
- Empty big (1, 0) | |
- Pour from small to big (0, 1) | |
- fill small (3, 1) | |
- pour small to big (0, 4) | |
Problem 2 --- Small = 5, Big = 7, Goal = 1 | |
- Start (0, 0) | |
- fill small (5, 0) | |
- pour small into big (0, 5) | |
- fill small (5, 5) | |
- pour small into big (3, 7) | |
- Empty big (3, 0) | |
- pour small into big (0, 3) | |
- fill small (5, 3) | |
- pour small into big (1, 7) | |
Problem 3 --- Small = 7, Big = 11, Goal = 3 | |
- Start (0, 0) | |
- fill small (7, 0) | |
- pour small into big (0, 7) | |
- fill small (7, 7) | |
- pour small into big (3, 11) | |
=end | |
def fill_jugs(small_jug_max, big_jug_max, goal) | |
# Print steps to console | |
small_jug = 0 | |
big_jug = 0 | |
puts '- Start (0, 0)' | |
while small_jug != goal && big_jug != goal | |
if small_jug == 0 | |
small_jug = small_jug_max | |
puts "- Fill small (#{small_jug}, #{big_jug})" | |
elsif big_jug < big_jug_max | |
# pour small into big (0, 7) | |
total = small_jug + big_jug | |
big_jug = total > big_jug_max ? big_jug_max : total | |
small_jug = total - big_jug | |
puts "- Pour small into big (#{small_jug}, #{big_jug})" | |
else | |
# fill small (7, 7) | |
big_jug = 0 | |
puts "- Empty big (#{small_jug}, #{big_jug})" | |
end | |
end | |
puts "Finished!\n\n" | |
end | |
fill_jugs(3, 5, 4) | |
fill_jugs(5, 7, 1) | |
fill_jugs(7, 11, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment