JavaScript : Repetition Statements IV


  1. Be able to use repetition statements that function correctly even if there is no specific item to process;
  2. Be able to correctly nest a conditional structure in a repeating loop.

 Your Task, Your Challenge 

Le robot trieur de lettres

Write your code so that the robot sorts all the letters into the colored boxes.

Each day, the mail carrier puts a stack of letters into the mailbox. The envelopes come in three different colors – yellow, red and green. The robot must sort each letter into the box with the same color as the envelope. At the end of the program, the robot must return to the mailbox to be ready for the next day. Note, it is possible that on some days the mail carrier will not put any letters into the mailbox – so the robot will begin its task even though the mailbox is empty.

The robot can carry out 2 actions:

  1. goToBox ('which'); where 'which' is either 'Mail' (= go to the mailbox), or 'yellow' (= go to the yellow box), 'red' (= go to the red box) or 'green' (= go to the green box);
  2. letter ('do'); where 'do' may be 'take' or 'put'.

The robot can also carry out 3 tests:

  1. aLetterInPincer () tests whether the robot has a letter in its pincer claw after collecting the mail from the mailbox;
  2. letterHeldYellow () tests whether the letter it is holding is yellow or not;
  3. letterHeldRed () tests whether the letter it is holding is red or not;

 Conditional and Repetitive Statements 

In this exercise, you will note that a conditional is required to sort the letters into the right boxes based on their color. This will have to be repeated as long as there is another new letter for the robot to take from the mailbox.

You need to put the statements in the correct order to solve this problem.

Good luck!