In the process of preparing for coding tests using Kotlin, one of the problems many face is understanding and solving various algorithmic problems. In this course, we will learn how to easily understand and solve problems based on ancient narratives related to Jumong by solving an economical algorithm problem titled ‘Jumong’s Command’.
Problem Description
Jumong commanded his army to defeat the enemies in the north and establish his kingdom. His command instructed each soldier to take a specific action. In this problem, when there are N soldiers, we need to determine what action each soldier will take.
The problem is as follows:
Problem: Jumong’s Command
Jumong has N soldiers. Each soldier is represented by a random number from 1 to 100, and Jumong commands soldiers with even numbers to “Move forward!” and those with odd numbers to “Step back!”.
Write a program that counts the number of even and odd soldiers from the given list of N soldier numbers and outputs each command.
Input
The first line contains the number of soldiers N (1 ≤ N ≤ 1000). The second line contains N soldier numbers separated by spaces.
Output
Print the commands based on each soldier's even/odd status. Output "Move forward!" or "Step back!" over N lines.
Example Input
5 1 2 3 4 5
Example Output
Step back! Move forward! Step back! Move forward! Step back!
Problem Solving Process
Now let’s look at how to solve this problem step by step. We will use Kotlin to solve it.
Step 1: Get Input
First, we need to receive input from the user. We can use the readLine()
function to get the input values.
Step 2: Convert to Number List
Since the entered numbers are separated by spaces, we need to convert them into a list. We will use Kotlin’s split()
method to split by spaces.
Step 3: Determine Even/Odd and Print Commands
Now, we can loop through all soldiers, check whether each number is even or odd, and print the corresponding command. We can use Kotlin’s if
statement to evaluate the conditions.
Code Example
fun main() { // Step 1 - Get Input val n = readLine()!!.toInt() // Number of soldiers val soldiers = readLine()!!.split(" ").map { it.toInt() } // List of soldier numbers // Step 3 - Determine Even/Odd and Print Commands for (soldier in soldiers) { if (soldier % 2 == 0) { println("Move forward!") } else { println("Step back!") } } }
Summary of the Entire Process
The process of solving the problem can be summarized as follows:
- Read the given input.
- Convert the entered numbers into a list.
- Determine the even/odd status of each soldier and print the commands.
Conclusion
Through this course, we learned how to solve the Jumong’s Command problem and how to use Kotlin. Algorithm problems can be presented in various forms, and understanding the fundamental problem-solving structure and approach is essential. Let’s continue to enhance our algorithm skills by practicing different problems!