logo CodeStepByStep logo

toboggan2

Related Links:

Write a function named toboggan2 (similar to the previous exercise, toboggan) that simulates a toboggan sliding down a repeating ski slope and counts the number of trees it would hit. The difference between this exercise and the previous exercise is that we will explore 5 possible toboggan paths and multiply the number of trees hit between them.

As in the previous problem, a map of the ski slope is stored in a file whose name is passed to your function as a parameter. The file contains a grid of open squares (.) and trees (#) such as the following file, slope.txt:

..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#

You should simulate the toboggan's movement down this slope. The toboggan starts on the square in the top-left corner and needs to reach the bottom (below the bottom-most row on your map). In the last exercise the toboggan always went down 1, right 3. In this exercise, the toboggan can choose one of the following movement patterns to repeat all the way down the slope:

  • Down 1, right 1.
  • Down 1, right 3. (the pattern from the previous exercise)
  • Down 1, right 5.
  • Down 1, right 7.
  • Down 2, right 1.

If you simulated the five movement patterns repeatedly in the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336. So the call of toboggan("slope.txt") would return 336. Note that the toboggan does not have the option of changing its movement style when it is partway down the slope; it repeats a single movement pattern all the way down the slope.

You may assume that the file exists and is readable, that it follows the format described above, and that the slope is of size at least 2x2.

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.