troubleshooting Question

how to solve 2 jug puzzle with random moves

Avatar of feliciayong
feliciayong asked on
Java
5 Comments1 Solution3917 ViewsLast Modified:
Objective
To write a program to solve a puzzle by guessing random solutions.
Important information  The Jugs Puzzle
In this old puzzle you are given an empty 5-litre jug, an empty 8-litre jug, and a sink with a tap.
The aim of this puzzle is to leave an exact number of litres of water in one of the jugs. When
solving this puzzle you are only allowed to do the following things:
" Fill up a jug from the tap.
" Empty a jug down the sink.
" Transfer water from one jug to another until either the source jug is empty or the
destination jug is full.
Even with just these moves it is possible to isolate precisely 0, 1, 2, 3, 4, 5, 6, 7, or 8 litres.
Note: for a given amount, there are multiple ways to isolate it.
Example
If we want to isolate exactly 2 litres we could:
Fill up the 5 litre jug
Transfer the 5 litre jug to the 8 litre jug
Fill up the 5 litre jug
Transfer the 5 litre jug to the 8 litre jug
We now have a full 8 litre jug and, most importantly, exactly 2 litres in the 5 litre jug. Satisfy
yourself that it is possible to isolate other amounts.
Sample run
-> java RandomSearch 4
Moves that can isolate 4 litres
starting with two empty jugs:
Fill J5
Transfer J5 to J8
Fill J5
Transfer J5 to J8
Empty J8
Transfer J5 to J8
Fill J5
Transfer J5 to J8
Fill J5
Transfer J5 to J8
Tried: 378580210 moves.

Your Task
Write a Java program called RandomSearch.java that:
1. Gets an integer amount between 0 and 8 from the command line.
2. Randomly generates sequences of moves and tests each sequence to see if it isolates
amount litres in one of the jugs.
3. When a sequence that isolates amount litres is found, displays this sequence and the
number of moves that the program guessed before finding this solution.

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros