Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # SETUP
- n = 3 # number of jugs
- j[1] = 17 ; j[2] = 16 ; j[3] = 15 # capacity of jugs
- # note: jug #0 is the "tub", with unlimited capacity
- # given a state, determine whether it's a goal state
- define isgoal(state) {
- return (amt(state, 1) == 8) + (amt(state, 2) == 8) + (amt(state, 3) == 8) >= 2
- }
- # a state is represented with one base-b digit for each jug's current amount.
- # state = 5b^2 + 4b + 3 means 3 in jug #1, 4 in jug #2, and 5 in jug #3
- b = 20
- # given a state, return the amount currently in the xth jug
- define amt(state, x) { if (x == 0) return 9999 ; return state / b^(x-1) % b }
- # given a state, return the remaining capacity in the xth jug
- define cap(state, x) { if (x == 0) return 9999 ; return j[x] - amt(state, x) }
- define min(g, h) { if (g < h) return g ; return h }
- # given a state, return the state you get pouring from x to y
- define pour(state, x, y) {
- p = min(amt(state, x), cap(state, y)) # amount that actually gets poured
- if (x) state -= p * b^(x-1)
- if (y) state += p * b^(y-1)
- return state
- }
- # SOLVE THE PROBLEM
- q[0] = 0 # the starting state
- qk = 1 # current size of the queue
- for (qj = 0 ; qj < qk ; ++qj) {
- state = q[qj]
- if (isgoal(state)) break
- for (x = 0 ; x <= n ; ++x) { # the jug I'm pouring from
- for (y = 0 ; y <= n ; ++y) { # the jug I'm pouring to
- if (x == y) continue
- newstate = pour(state, x, y)
- if (explored[newstate]) continue
- explored[newstate] = 1
- q[qk++] = newstate # Add the new state to the queue
- parent[newstate] = state
- jfrom[newstate] = x
- jto[newstate] = y
- }
- }
- }
- # PRINT THE SOLUTION
- while (state) {
- solution[sj++] = state
- state = parent[state]
- }
- while (sj) {
- state = solution[--sj]
- x = jfrom[state] ; y = jto[state]
- if (!x) print "Fill jug #", y, " "
- if (!y) print "Empty jug #", x, " "
- if (x && y) print "Pour from jug #", x, " to jug #", y, " "
- for (x = 1 ; x <= n ; ++x) print amt(state, x), "/", j[x], " "
- print "\n"
- }
- halt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement