Home > OS >  How to add only the required number of inputs in an array in Kotlin?
How to add only the required number of inputs in an array in Kotlin?

Time:10-19

My question is: How to add only the required number of inputs in an array in Kotlin?

Input Format

  1. The first line of input will contain a single integer, the number of test cases. Then the test cases follow.
  2. Each test case consists of 2 lines of input.
  3. The first line of input of each test case contains a single integer, N, which is the total number of problems that the person has added to his to-do list.
  4. The second line of input of each test case contains N space-separated integers (eg: d1, d2, d3.....)

My doubt is how to mention the required number of inputs (that should only be counted in the array)

Link to the original problem:

Sample Inputs

Inputs

Sample Output

Outputs

Please help me to solve this in Kotlin.

My incompleted code without the 3rd step

fun main() {
val n = readLine()!!.toInt()
repeat(n) {
    val difficultyRating = readLine()!!.split(" ").map { it.toInt() }

    difficultyRating
        .count { it >= 1000 }
        .let { println(it) }
     }
}

CodePudding user response:

This is how we need to code to solve this. (Thank you for the helps)

fun main() {
val n = readLine()!!.toInt()  //number of times the program should be repeated
repeat(n) {
    val x = readLine()!!.toInt()
    /*this is how we can explicitly mention that "n" number of inputs only should be
    considered when running the program  using (take() function)*/
    val difficultyRating = readLine()!!.split(" ").map { it.toInt() }.take(x)

    difficultyRating
        .count { it >= 1000 }
        .let { println(it) }
    }
}

CodePudding user response:

It's more typical to work with Lists than arrays. Since all the difficulty ratings come in on a single line, instead of repeating or using a loop, you can split the input string. After you split them into a List, they are still Strings, so you you need to convert when comparing them to a number.

fun main() {
    val numberOfTestCases = readln().toInt()
    repeat(numberOfTestCases) {
        readln() // we don't need to read number of items, but we need to skip the line
        readln().split(" ")
            .count { it.toInt() > 1000 }
            .let { println(it) }
    }
}
  • Related