I have a task in JetBrains Academy: "Write a program that reads an unsorted list of integers and two numbers: P and M. The program needs to check whether P and M occur in the list.
The first line contains the size of the list. The next N lines contain the elements of the list. The last line contains two integer numbers P and M separated by a space.
If both numbers occur in the list you need to print YES, otherwise – NO."
My code:
fun main() {
val size = readln().toInt()
val mutList: MutableList<Int> = mutableListOf()
val (a, b) = readln().split(" ")
val p: Int = a.toInt()
val m: Int = b.toInt()
for (i in 0 until size) {
mutList.add(readln().toInt())
}
if(p in mutList || m in mutList) {
print("YES")
} else {
print("NO")
}
}
And I have this error:
Error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.base/java.util.Collections$SingletonList.get(Collections.java:4849)
at MainKt.main(main.kt:4)
at MainKt.main(main.kt)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.jetbrains.kotlin.runner.AbstractRunner.run(runners.kt:70)
at org.jetbrains.kotlin.runner.Main.run(Main.kt:188)
at org.jetbrains.kotlin.runner.Main.main(Main.kt:198)
I'm newbie at Kotlin and coding at all, but I keep trying to learn some. What's wrong in my code?
CodePudding user response:
As per the question, you need to input the list elements before P and M. Also, you have to print "YES" when both numbers occur in list i.e. you need to use &&
instead of ||
.
fun main() {
val size = readln().toInt()
val list = List(size) { readln().toInt() }
val (p, m) = readln().split(" ").map { it.toInt() }
if(p in list && m in list) {
println("YES")
} else {
println("NO")
}
}