Trying to find the lowest number in a kotlin array

Viewed 2133

Kotlin newbie here, I'm trying to Write a program that finds the minimum value of N numbers. The first line contains the number N. The second line contains N numbers separated by spaces. Output an integer number which is the minimum of N numbers. So far I'm getting a null error, so I know the problem is in adding numbers to the array. Here is my code:


fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val num1: Int = scanner.nextInt()
    var nums = arrayListOf<Int>()
    val smallestElement = nums.min()
    repeat (num1) {
        nums.add(scanner.nextInt())
    }
    println(smallestElement)

}
2 Answers

java.util.Scanner is so slow, try considering readLine it is optimal for most of the case, and using System.`in`.bufferedReader().readLine() is the fastest but increases heap by creating a buffer.

And the reason you were getting null was because you were trying to get the minimum value at of an empty array. At the time you called ArrayList.min() you did not had added any element into it.

private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()

fun main(args: Array<String>) {
    val num1: Int = readInt()
    var nums = IntArray(num1) { readInt() }
    println(nums.min())
}

And if you don't mind, instead of storing all the numbers into array and then comparing all the element against minimum you can directly check for minimum elements without creating an array:

private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()

fun main(args: Array<String>) {
    val num1: Int = readInt()
    var min = Int.MAX_VALUE
    repeat(num1) {
        val i = readInt()
        if (i < min) min = i
    }
    println(min)
}

Just invert the order:

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val num1: Int = scanner.nextInt()
    var nums = arrayListOf<Int>()
    repeat (num1) {
        nums.add(scanner.nextInt())
    }
    val smallestElement = nums.min()  // < ----------- here
    println(smallestElement)

}

Related