Home > database >  We need to create function minmax that takes integer array and a lambda expression as arguments and
We need to create function minmax that takes integer array and a lambda expression as arguments and

Time:06-15

Iam new to programing and trying my best but now I'm stucK on this. Please help. We need to create function minmax that takes integer array and a lambda expression as arguments and return minimum or maximum based on lambda passed

fun main(args: Array<String>) {

val numsCount=readLine()!!.trim().toInt()

val nums = Array<Int>(numsCount, {0}) 
for (i in 0 until numsCount) { 
val numsItem=readLine()!!.trim().toInt()

nums[i] = numsItem

}

val type =readLine()!!.trim().toInt()!=0 
var lambda= {a: Int, b: Int -> a>b}

if(!type){

lambda {a: Int, b: Int -> a<b}

val result = minmax(nums, lambda)

println(result)

}

CodePudding user response:

There is no point using a lambda in this particuliar case but here is how you do it :

 fun minmax(nums: Array<Int>, minMaxCallback: (Int?, Int?) -> Unit) =
    minMaxCallback(nums.minOrNull(), nums.maxOrNull())

Call with :

minmax(nums) { min, max ->

    }

CodePudding user response:

Firstly, I would strongly advise you to use indentation to show the structure of your code.

Here is my suggested solution, in which I've also applied some further changes, such as using the newer readln() instead of readLine()!!, and calling the lambda variable a more descriptive name.

fun main() {
    val numsCount = readln().trim().toInt()
    val nums = Array(numsCount) { readln().trim().toInt() }

    val type = readln().trim().toInt() != 0

    val minOrMax = if (type) {
        { min: Int, current: Int -> current < min }
    } else {
        { max: Int, current: Int -> current > max }
    }

    val result = minmax(nums, minOrMax)
    println(result)
}

fun minmax(nums: Array<Int>, selectItem: (Int, Int) -> Boolean): Int {
    if (nums.isEmpty())
        throw NoSuchElementException()

    var currentSelectedItem = nums[0]
    for (i in 1 until nums.size) {
        if (selectItem(currentSelectedItem, nums[i]))
            currentSelectedItem = nums[i]
    }

    return currentSelectedItem
}
  • Related