Interview Practice Questions: Meet the robots
Read full article from Interview Practice Questions: Meet the robots
Two robots land with their parachutes on an infinite one-dimensional number line. They both release their parachutes as soon as they land and start moving. They are allowed only to make use of the following functions.
I. moveLeft() // robot moves to left by 1 unit in 1 unit time
II. moveRight() // robot moves to right by 1 unit in 1 unit time
III. noOperation() // robot does not move and takes 1 unit time
IV. onTopOfParachute() // returns true if the robot is standing on top of either of the parachute, else false
V. didWeMeet() // returns true if the robot meets to the other robot, else false
II. moveRight() // robot moves to right by 1 unit in 1 unit time
III. noOperation() // robot does not move and takes 1 unit time
IV. onTopOfParachute() // returns true if the robot is standing on top of either of the parachute, else false
V. didWeMeet() // returns true if the robot meets to the other robot, else false
Write a function in order to make the robots meet each other. Robots will be executing the same copy of this function.
void meetRobots(Robot r1,Robot r2) {
r1.moveLeft(), r2.moveLeft();
while(!r1.onTopOfParachute() && !r2.onTopOfParachute()) {
r1.moveLeft(), r2.moveLeft();
}
if(r1.onTopOfParachute()) {
while(!r2.didWeMeet()) {
r2.moveRight(),r1.noOperation();
}
} else {
while(!r1.didWeMeet()) {
r1.moveRight(),r2.noOperation();
}
}