Question

water jug problem in recursive

Asked by: wuyinzhi

dear experts, this is not homework or assignment, i just try to solve this but i am stuck so i am so curious. the question is a water jug problem, where:

A : max capacity 7 litres
B : max capacity 4 litres
C : max capacity 3 litres

start position is A filled with 7 litres, B and C are empty.
i want the result is A = 2, B = 2, C = 3

how to solve this recursively? vb is prefer since i am familiar with vb.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-09-11 at 08:26:44ID23723291
Tags

VB

Topics

C++ Programming Language

,

Algorithms

,

Visual Basic Programming

Participating Experts
3
Points
150
Comments
23

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. 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.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Java code to calculate the amount of time it takes to fill the p…
    Need to write a program that calculates the amount of time it will take to fill the pools with water. Pool volume L*W*D. Pool capacity L*W*D*Capacity. The rate flow is 50.0 gal/min. Capacity is 7.5 gal/cubic foot This will enable the company to charge for pool fill-up on the...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: itsmeandnobodyelsePosted on 2008-09-11 at 08:59:50ID: 22451315

>>>> this is not homework or assignment,
Hmmm. What is it then?

>>>> i want the result is A = 2, B = 2, C = 3
Can you tell what the goal of the task is?

 

by: wuyinzhiPosted on 2008-09-11 at 09:36:59ID: 22451713

i just learn about recursive and i was amazed with the logic, so i just want to learn. some questions came up: water jug problem at die hard 3 movie, this puzzle i posted, permutation, etc, but i still failed to solve them.

sorry i don't understand what do you mean with the goal of the task, i think it's just a common puzzle game, there are some more difficult variants but i think i can start learning from this first.

 

by: wuyinzhiPosted on 2008-09-11 at 09:41:23ID: 22451767

also please check my questions history, i am not new member, i've been working as programmer since 1999 and never touch school stuff anymore :)

 

by: FentonEngPosted on 2008-09-11 at 09:55:18ID: 22451942

It's quite a nice algorithm to develop, however a google search revealed a LOT of matches - you should look a little harder ;)

Here's a nice little page which because it has a few applets to play with, will probably explain it clearer than I can using text and code on here

http://www.cut-the-knot.org/ctk/Water.shtml

 

by: wuyinzhiPosted on 2008-09-11 at 10:00:04ID: 22452002

thx for the link, FentonEng. Actually i have read the link you gave, also in wikipedia about search algorithm, i understand about the logic but it's difficult for me to implement it with the recursive function.

 

by: FentonEngPosted on 2008-09-11 at 10:11:29ID: 22452121

Normally recursion side-steps some logic in return for lots of nested functions calls. However in this instance I believe it would be far easier to have a loop do all of the logical processing and have you put in a control statement to check for your target capacity. You are essentially going to have to "step" through the algorithm, recursion is only going to hinder you in this case.

Have you got any base code you have started to work on yet?

 

by: itsmeandnobodyelsePosted on 2008-09-11 at 11:49:07ID: 22453211

>>>> sorry i don't understand what do you mean with the goal of the task
I mean that you didn't mention that the water should be equally divided into the jugs (according to the link Fenton showed). I am still unsure why 2 2 3 is a solution then? Shouldn't it 2 litres in the last jug as well?

>>>> i think it's just a common puzzle game
I know a variant of the puzzle where you have to gauge a given amount into one of the jugs, e. g. 2 litres in your sample, though I don't know whether the solutions were similar.

 

by: FentonEngPosted on 2008-09-11 at 11:58:32ID: 22453345

I do think you (wuyinzhi) should play with the triangular co-ordinates applet with the trace function "on", to see exactly what is happening in geometric terms.

If I understand your question correctly you are interested in how the algorithm is developed, over trying to generate a particular solution. The problem does have a specific end criteria, so if you *did* want 2, 2, 3 as a valid solution, then the algorithm could grant you it. I am going to side with itsmeandnobodyelse (possible spelling error in there sorry!) and ask you for a slightly rephrased and more focused question

 

by: ozoPosted on 2008-09-11 at 16:51:53ID: 22456101

A = 0, B = 0, C = 0
A = 7, B = 0, C = 0
A = 3, B = 4, C = 0
A = 3, B = 1, C = 3
A = 6, B = 1, C = 0
A = 6, B = 0, C = 1
A = 2, B = 4, C = 1
A = 2, B = 2, C = 3

 

by: wuyinzhiPosted on 2008-09-11 at 19:51:32ID: 22456781

morning all,

yes i think ozo's comment made it clear. what i want to develop is the algorithm and display the steps of how the jugs are transfer each other till finally display 2,2,3.

my analysis so far:

- there are 6 possible moves:
 A fill B
 A fill C
 B fill A
 B fill C
 C fill A
 C fill B

the problem of my code is it returns out of stack because there are some states (ex. 7,0,0) repeat infinitely, should i save every states in table/array?



 

Private Sub Form_Load()
    puzzle 7, 0, 0
End Sub
 
Private Sub puzzle(ByVal t7 As Integer, ByVal t4 As Integer, ByVal t3 As Integer)
Dim i As Integer
 
    If t7 = 2 And t4 = 2 And t3 = 3 Then
        MsgBox "complete."
    Else
    
                i = fill(t7, t4, 4)
                puzzle abc(t7 + t4 - 4), i, t3
                i = fill(t7, t3, 3)
                puzzle abc(t7 + t3 - 3), t4, i
                i = fill(t4, t3, 3)
                puzzle t7, abc(t4 + t3 - 3), i
                i = fill(t4, t7, 7)
                puzzle i, abc(t4 + t7 - 7), t3
                i = fill(t3, t4, 4)
                puzzle t7, i, abc(t3 + t4 - 4)
                i = fill(t3, t7, 7)
                puzzle i, t4, abc(t3 + t7 - 7)
        
    End If
    
End Sub
 
Private Function abc(ByVal n As Integer) As Integer
    If n < 0 Then
        abc = 0
    Else
        abc = n
    End If
End Function
 
Private Function fill(ByVal source As Integer, ByVal dest As Integer, ByVal capacity As Integer) As Integer
 
    fill = dest + source
    If fill > capacity Then fill = capacity
 
End Function
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window

 

by: ozoPosted on 2008-09-11 at 20:02:52ID: 22456823

What I did was to not save states that had been generated before.
I also included the moves
fill A
fill B
fill C
empty A
empty B
empty C
but it turned out that the shortest path did not use any of them except for fill A

 

by: FentonEngPosted on 2008-09-11 at 20:06:45ID: 22456839

I thought you wanted the general algorithm not a specific case! I see now :)
 
6 moved is the minimum from 7-0-0 to 3-2-2.
 
Your code sample has an error in the implementation for the "fill" function. Your code sample will infinitely recurse
 
puzzle 7, 4, 0
 
Until a stack overflow occurs
 
*hint: You need to subtract from the source at some point
 
I have posted this as a snippet as the submit button kept complaining about the text box being empty!!!!!!

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: wuyinzhiPosted on 2008-09-12 at 00:07:58ID: 22457671

Dim state(1000) As String
Dim l As Long
 
Private Sub Form_Load()
    l = 0
    puzzle 7, 0, 0
End Sub
 
Private Sub puzzle(ByVal t7 As Integer, ByVal t4 As Integer, ByVal t3 As Integer)
Dim i As Integer
 
    state(l) = t7 & t4 & t3
    Debug.Print state(l)
    l = l + 1
 
    If t7 = 2 And t4 = 2 And t3 = 3 Then
        MsgBox "complete."
    Else
    
                i = fill(t7, t4, 4)
                If isValid(abc(t7 + t4 - 4) & i & t3) Then puzzle abc(t7 + t4 - 4), i, t3
                i = fill(t7, t3, 3)
                If isValid(abc(t7 + t3 - 3) & t4 & i) Then puzzle abc(t7 + t3 - 3), t4, i
                i = fill(t4, t3, 3)
                If isValid(t7 & abc(t4 + t3 - 3) & i) Then puzzle t7, abc(t4 + t3 - 3), i
                i = fill(t4, t7, 7)
                If isValid(i & abc(t4 + t7 - 7) & t3) Then puzzle i, abc(t4 + t7 - 7), t3
                i = fill(t3, t4, 4)
                If isValid(t7 & i & abc(t3 + t4 - 4)) Then puzzle t7, i, abc(t3 + t4 - 4)
                i = fill(t3, t7, 7)
                If isValid(i & t4 & abc(t3 + t7 - 7)) Then puzzle i, t4, abc(t3 + t7 - 7)
        
    End If
    
End Sub
 
Private Function isValid(ByVal s As String) As Boolean
Dim i As Long
Dim res As Boolean
 
    res = True
    For i = 0 To l
        If state(i) = s Then
            res = False
            Exit For
        End If
    Next i
    
    isValid = res
    
End Function
 
Private Function abc(ByVal n As Integer) As Integer
 
    If n < 0 Then
        abc = 0
    Else
        abc = n
    End If
    
End Function
 
Private Function fill(ByVal source As Integer, ByVal dest As Integer, ByVal capacity As Integer) As Integer
 
    fill = dest + source
    If fill > capacity Then fill = capacity
 
End Function
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:

Select allOpen in new window

 

by: wuyinzhiPosted on 2008-09-12 at 00:11:20ID: 22457682

hmm.. i see what FentonEng's problem with text box :)
finally i solve the problem with my method: save previous states.
but i think it's different with ozo's method and other experts here. would  you share the code since this is just for learning purpose?

                                              
1:
2:
3:

Select allOpen in new window

 

by: ozoPosted on 2008-09-12 at 00:35:42ID: 22457764

It is a different method than what I did, but there are many methods that work.
Recursion may be more natural for a depth first search, but I did a breadth first search so I can stop when I find the shortest path,
and only used recursion to print the path.

 

by: FentonEngPosted on 2008-09-13 at 06:01:21ID: 22466989

Your fill function is still broken. I keep thinking that a tree would solve the general case more efficiently, but you are limited with respects to that in VB

 

by: wuyinzhiPosted on 2008-09-13 at 07:22:46ID: 22467611

hi FentonEng n other experts, can you provide some code/clue how to solve the problem maybe in another language? actually i just curious how it can be done with recursion effectively.  I read all of your comments but still can't get it.

 

by: FentonEngPosted on 2008-09-13 at 10:49:16ID: 22468452

I would break the problem down into "moves" ie transfers (from one to another), fills (fill one jar to the top) and empties (empty a jar) . Generate a "tree" data structure based on combinations and permutations of the said "moves" then apply an algorithmic approach to clip away the tree using constraints and "bad" moves.

What is left will be a family of solutions, which I could then simply traverse in turn to find the shortest one.

I would stay away from recursion until you can get the basic steps and a plan together. I really don't see any need for it, except perhaps for the "tree" facility.

Once I was satisfied I had the "tree" approach covered, I would look at ways of "removing" the tree and performing a direct determined calculation for each step.

There is probably a standard approach for this type of problem, but that is how I would approach the problem from first principles.

FWIW: By "tree" I *mean* a hierarchial data structure, the tree does not have a pre-determined number of roots, branches, nodes, children or any imposed limits whatsoever beyond that of a standard heirarchial structure.

 

by: wuyinzhiPosted on 2008-09-14 at 20:59:29ID: 22475840

dear FentonEng, i see your method is similar with ozo's, using fill and empty procedure/function. Something i don't understand is why we should fill and empty? since i guess this problem is about transfer x to y?

 

by: ozoPosted on 2008-09-15 at 10:16:25ID: 22480713

not necessary in this particular problem, but other problems in this genre may include them.

 

by: FentonEngPosted on 2008-09-16 at 18:20:59ID: 22494739

The fill/empty were just "possible" moves as your original question didn't specify any particular rules over handling the jugs itself.

*Just* having transfers makes the problem simplify a fair bit, but you haven't made a transfer function yet! You *literally* have a fill function and not a transfer function. That was a subtle error and point of your source code I was hoping you had seen.

Firstly, correct your transfer function, then you may be able to see if the rest of your program is close to a solution.

You seem to understand the recursion process itself, so your next task would be a case of converting an algorithm into an iterative process, then recursing through the steps.


 

by: wuyinzhiPosted on 2008-09-16 at 19:54:31ID: 22495106

ok FentonEng, i'll try your suggestion, thanks. Sorry for this long thread as i am doing this for fun and learning purpose, so my responses maybe not so fast.

 

by: FentonEngPosted on 2008-09-20 at 04:15:13ID: 22529181

Not a problem, however, make sure you are a bit more specific with your questions in the future. This one is very very "open ended"!

Write it all out on paper, you can't really "build" a tree directly to my knowledge in VB (there may be a way by storing addresses as integers) but you will use recursion to emulate the tree.

You won't need to save any states if your program logic can steer around any infinite loops

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...