31
loading...
This website collects cookies to deliver better user experience
command units
.forward
, up
, down
.command units
, we need to tokenize it to command
and units
.forward
, we will increase the XPosition by units
. If the command token is up
, we will decrease the YPosition by units
. Finally, if the command token is down
, we will increase the YPosition by units
.SUBMARINE_MOVEMENT(Instructions)
INPUT: A list of string instructions
OUTPUT: The product of the final horizontal position times the final vertical position
XPosition = 0
YPosition = 0
FOREACH(Instruction in Instructions)
(instruction, units) = TOKENIZE(instruction)
SWITCH instruction
CASE "forward"
XPosition = XPosition + units
CASE "up"
YPosition = YPosition - units
CASE "down"
YPosition = YPosition + units
END SWITCH
END FOREACH
RETURN XPosition * YPosition
int xPosition = 0;
int yPosition = 0;
foreach(string instruction in data)
{
string[] commands = instruction.Split(" ");
switch(commands[0])
{
case "forward":
xPosition += int.Parse(commands[1]);
break;
case "up":
yPosition -= int.Parse(commands[1]);
break;
case "down":
yPosition += int.Parse(commands[1]);
break;
}
}
return xPosition * yPosition;
[command, unit]
array. Then, a switch statement parses the command
argument and performs the appropriate position calculations. up
and down
commands change the pitch angle of the submarine. Since only the pitch angle is affected, the forward
command changes the vertical and horizontal positioning. Now forward
adds X units on the horizontal position and pitch_angle
* X units on the vertical.int xPosition = 0;
int yPosition = 0;
int aim = 0;
foreach (string instruction in data)
{
string[] commands = instruction.Split(" ");
switch (commands[0])
{
case "forward":
xPosition += int.Parse(commands[1]);
yPosition += int.Parse(commands[1]) * aim;
break;
case "up":
aim -= int.Parse(commands[1]);
break;
case "down":
aim += int.Parse(commands[1]);
break;
}
}
return xPosition * yPosition
aim
to store the pitch angle of the submarine.up
and down
commands, no longer affect the ship's vertical position, adjusting the pitch angle instead.forward
command, calculates the horizontal movement of the ship by adding X units to the horizontal position, as well as calculating the vertical position. The vertical position is the product of the traversal angle times X units of movement.