Author: James D. Skrentny, skrentny@cs.wisc.edu copyright 2009-2012 all rights reserved Our previous Ball2Right solution would fail if there were more cups and/or more balls. Let's make our code more ROBUST so that it is able to handle the problem of a single rainbow ball possibly being in the way. Ball Move Language: *The form of our language is .() .on() e.g., greenBall.on(2) .step() e.g., greenBall.step("right") .jump() e.g., greenBall.jump("right") Given: 3 cups in a row numbered 1, 2, 3 1 green ball (named greenBall) 1 rainbow ball (named rainbowBall) the balls can start on any one of the cups Goal: Move green ball to cup on the right (cup #3). Note: Again, if green ball is already on right cup then nothing need be done. Solution: --------- if (greenBall.on(2)) { if (rainbowBall.on(3)) { rainbowBall.jump("left"); } greenBall.step("right"); } else if (greenBall.on(1)) { if (rainbowBall.on(3)) { rainbowBall.step("left"); } if (rainbowBall.on(2)) { greenBall.jump("right"); } } Trace the code fragment above to see if it WORKS. Note: Design a solution that addresses the underlying logic of the problem: 1. Where's the green ball? (first level decision) 2. Is the rainbow ball in the way? (second level decision) Now, let's make the problem more GENERAL by allowing 0 or 1 rainbow balls. Solution: --------- Note: added the else part after the last if below. if (greenBall.on(2)) { if (rainbowBall.on(3)) { rainbowBall.jump("left"); } greenBall.step("right"); } else if (greenBall.on(1)) { if (rainbowBall.on(3)) { rainbowBall.step("left"); } if (rainbowBall.on(2)) { greenBall.jump("right"); } else { greenBall.step("right"); greenBall.step("right"); } } Does this WORK? TRACE it for the different initial states.