Tuesday, July 29, 2014

Solution: A Train using Nested Loops

1.  Assume we start drawing the train from the leftmost bottom corner, with Pro-Bot facing forward.

Here is the code for the engine:

  Fd 6
  Rt
  Fd 2
  Lt
  Fd 3
  Rt
  Fd 2
  Rt
  Fd 3
  Lt
  Fd 6
  Rt
  Fd 6
  Rt
  Fd 10
  Bk 12
  Rt

At this point, the engine is done and the Pro-Bot is ready to start drawing the coaches. The 3 coaches are similar, which means we can use Nested Loops for drawing them. Here is the code for the train with 3 coaches and the connectors:

  Rpt 3 [           // the 3 here refers to the number of coaches
  Rpt 3 [           // the 3 here refers to the 3 sides of the square that forms a coach
  Fd 6
  Rt
  ]
  Fd 6
  Bk 8
  Rt
  ]



2.  To draw the train with 5 coaches, the only change required is to change the 3 in the outer loop to 5. The code for the engine remains the same. The code for the coaches is now:

  Rpt 5 [           // the 5 here refers to the number of coaches
  Rpt 3 [           // the 3 here refers to the 3 sides of the square that forms a coach
  Fd 6
  Rt
  ]
  Fd 6
  Bk 8
  Rt
  ]



3.  To draw the train with 20 coaches, the only change required is to change the number in the outer loop to 20. Everything else remains the same.

  Rpt 20 [         // the 20 here refers to the number of coaches
  Rpt 3 [           // the 3 here refers to the 3 sides of the square that forms a coach
  Fd 6
  Rt
  ]
  Fd 6
  Bk 8
  Rt
  ]

No comments:

Post a Comment