CEMC Banner

Problem of the Week
Problem C
Dog Bones

Elbashir wrote a computer program to control Scruffy the dog as he moves along a row of ten squares, some of which contain a bone, as shown.

Ten identical squares are placed horizontally side by side. Reading from left to right, there is a bone in the second, fifth, sixth, and seventh squares. All other squares are empty.

Elbashir wrote functions that allow Scruffy to move left or right a given number of squares, pick up a bone, or put down a bone. However, some care needs to be taken when using the functions. Scruffy can hold only one bone at a time, so cannot pick up a bone if he is already holding one. Similarly, he cannot put down a bone if he isn’t holding one. Trying to do either of these actions will result in an error and cause the program to stop.

When the program starts, Scruffy is in the leftmost square and is not holding a bone.

  1. Elbashir tries to run the following code, but it contains an error so the program stops. On which line of code does the program stop? Why?

    Line Number Code
    1 REPEAT 2 times:
    2 move 4 squares right
    3 pick up bone
    4 move 2 squares left
    5 put down bone
    6 end REPEAT
    7 move 1 square left
    8 pick up bone
    9 move 3 squares right
    10 put down bone
  2. Rewrite the code so that the program runs properly and once it’s finished, the bones are in the four rightmost squares. As an extra challenge, see if you can do this using only \(10\) lines of code.


Theme: Computational Thinking