Write a method named RainRisk
that processes a file of instructions to a ferry to maneuver it to avoid storms.
Your method accepts as its parameter a string representing the name of a file of commands for moving the ferry.
Your code should execute the commands and determine how far the ferry would move from its original position.
Each line of the input data contains an action followed by an integer value.
The actions are the following:
- Action
N
means to move the ferry north by the given value.
- Action
S
means to move the ferry south by the given value.
- Action
E
means to move the ferry east by the given value.
- Action
W
means to move the ferry west by the given value.
- Action
L
means to turn the ferry left (counter-clockwise) the given number of degrees, assumed to be a multiple of 90.
- Action
R
means to turn the ferry right (clockwise) the given number of degrees, assumed to be a multiple of 90.
- Action
F
means to move the ferry forward by the given value in the direction it is currently facing.
The ship starts by facing east.
Only the L
and R
actions change the direction the ship is facing.
For example, suppose the file named instructions.txt
contains the following text:
F10
N3
F7
R90
F11
F10
would move the ship 10 units east to (10, 0).
N3
would move the ship 3 units north to (10, 3).
F7
would move the ship 7 units east to (17, 3).
R90
would cause the ship to turn right by 90 degrees and face south.
F11
would move the ship 11 units south to (17, 8).
Your code should simulate all the movement instructions and then return the straight-line "Manhattan distance" from its original position, defined as the sum of the absolute x-distance and y-distance.
For the instructions shown previously, the ship's Manhattan distance is 17 + 8 = 25.
So the call of RainRisk("instructions.txt")
would return 25
.
You may assume that the file exists and is readable,
that it follows the format described above,
and that there will be at least one line of input in the file.
(This exercise is based on the Advent of Code 2020, day 12.)