Chapitre 6-5 : the trick of first and last

 The trick of first and last 

Let's say you had the task of looking down the street at 20 passing cars and, among these 20 cars, identifying the position of the first red car and the last. How would you go about it?

The first thing to do, of course, would be to use a counter variable so that you can stop after the twentieth car and also report the positions of the two red cars you're interested in.

We'll define two variables to hold these positions, first and last.

Each time a car passes, since we're not mind readers, it may be the last. So we'll systematically copy the position of any red car into the last variable.

The problem is trickier for the first red car. You have to copy its position into first, but above all, don't copy anything else at all, as this would erase the data. How do you do this?

The trick is to initialize the first variable with an impossible value, which will never correspond to a value in the counter variable. Before copying the position of the red car into first, we check that the value contained in first is indeed the impossible value. If not, nothing is written to first. If the impossible value is in first, we copy the counter value. Never again will any value be copied to first in this way, so the position of the first car will be there.

In concrete terms, the program looks like this:

1. Initialize the counter variable to 0
2. Initialize variable first to 0 (impossible value, as there will never be a car in position 0)
3. REPEAT
4.      Watch the passing car
5.      Adds 1 to the contents of the counter variable
6.      IF the passing car is red THEN
7.           Copies contents of counter to last variable
8.           IF the content of first is 0 THEN
9.                Copy the contents of counter to the first variable
10.           END IF
11.      END IF
12. UNTIL counter = 20
13. IF first > 0 THEN
14.      IF first = last THEN
15.           Displays: ("There was only one red car in position"), first
16.      ELSE
17.           Display ("The first red car was in position"), first
18.           Display ("and the last red car was in position"), last
19.      END IF
20. ELSE
21.      Display ("Of the 20 cars that passed, there were no red cars")
22. END IF

Once you've got the hang of this trick, you'll be ready to start the train scanning robot exercise.

Good work.