1. Problem Overview
This coding test problem is to implement the given conditions based on the orders that Jumong gave to his soldiers. The problem is as follows.
Problem Description
Jumong gives each soldier N
commands. Each command instructs them to move in a specific direction.
The soldiers receive and execute these commands. However, Jumong made a mistake during the command process and decided to ignore some commands.
Now, you need to write a program that calculates the final position based on the executed commands by the soldiers.
Format of Commands
- The commands are given as a list of strings:
["U", "D", "L", "R"]
. - “U” means to move up by one step, “D” means to move down by one step, “L” means to move left by one step, and “R” means to move right by one step.
- The number of commands is
1 ≤ N ≤ 1000
.
Input
The first line contains the number of commands N
,
and the next N
lines contain each command.
Output
Output the coordinates of the final position (x, y)
as integers.
The initial position is (0, 0)
.
2. Problem Solving Process
2.1. Understanding the Problem
To solve the problem, we need to implement the movement according to each command following specific rules.
The list of commands will be analyzed, and the coordinates will be updated according to each command.
2.2. Data Structure Design
We use the (x, y)
coordinates to store the final position.
It is initialized with x = 0, y = 0
.
2.3. Algorithm Design
We will read each command line by line and move in the corresponding direction.
In other words, the coordinates will be updated as follows based on each command:
"U"
:y += 1
"D"
:y -= 1
"L"
:x -= 1
"R"
:x += 1
2.4. Final Code Implementation
def final_position(commands):
x, y = 0, 0 # Initial position
for command in commands:
if command == "U":
y += 1
elif command == "D":
y -= 1
elif command == "L":
x -= 1
elif command == "R":
x += 1
return (x, y)
# Example input
N = int(input("Enter the number of commands: "))
commands = [input().strip() for _ in range(N)]
# Output final position
print(final_position(commands))
3. Examples and Tests
3.1. Test Cases
For example, if the following input is given:
5
R
R
U
D
L
When processing the above commands, the final position will be (1, 0)
.
4. Conclusion
In this process, we implemented an algorithm to calculate the final position of the soldiers based on Jumong’s commands.
We solved the problem through coordinate updates according to each command.
This simple problem helps us understand the basics of data structures and algorithm application.