-4

I'm using robot world for an assignment. we have to get to robot to go north 8 places then east 6 places. when we get to the point the robot has a choice to make. if there is an even number of beepers in that see the robot should face north and move one cell. if there is an odd number of beepers then it should face south and move one. I don't know what command to give the robot in the source code. my program runs when i just have

if(beeperPresent)) {
    turnLeft();
    move();
} else {
    turnRight();
    move();
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
Eoin Ronayne
  • 1
  • 1
  • 1
  • 1

3 Answers3

1

Eoin, an effective way of calculating odd or even numbers is to use the modulo operator. It's very simple.

if (number % 2 == 0) numberIsEven
if (number % 2 != 0) numberIsOdd

You could use this logic in your code to calculate if there are an even or odd number of beepers.

Gordonium
  • 3,389
  • 23
  • 39
1

Example:

int number1 = 1;
int number2 = 2;

if (number1 % 2 == 0) {
    // You won't get here
}

if (number2 % 2 == 0) {
   // You will get here
}

The "%" is called modulo, and it returns the remaining of the division.

  • 3 % 2, the remaining of 3/2 is 1, so you know it's odd
  • 4 % 2, the remaining of 4/2 is 0, so you know it's even
HLP
  • 2,142
  • 5
  • 19
  • 20
0

I think you are doing programming methodology course of Stanford university and having your assignment on Karel. Nice to see this. Coming back to your problem, for this case, you can use a counter to check how many beepers are present (initially set to Zero, just increment the counter if you pick a beeper). Pick beepers until all are picked up. Then, finally check if the counter is divisible by 2 or not to check its even or odd.