1

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)

}
ばらす
  • 11
  • 1
  • (Also worth pointing out that in general, you should prefer lists over arrays, as lists are much more flexible and better supported. Arrays are only needed for a few specific things such as varargs and interoperability with Java.) – gidds Jun 14 '22 at 20:42

2 Answers2

0

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 ->

    }
0

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
}
k314159
  • 5,051
  • 10
  • 32