Hey I am working in kotlin. I want to know is there any way when we entering value we know which value is smallest in the list.
For example
var userInputList = mutableList<Boolean>()
User Input Number -> 5
userInputList -> false
Again User Input Number -> 2
userInputList -> false, true
Again User Input Number -> 7
userInputList -> false, true, false
Again User Input Number -> 1
userInputList -> false, false, false, true.
Main thing I want to know, which one is smallest number.
CodePudding user response:
val list = mutableListOf<Int>()
while (true) {
val i = readln().toIntOrNull() ?: break
list.add(i)
val bools = list.fold(emptyList<Boolean>()) { acc, value ->
acc (value == list.minOrNull()!!)
}
println(list)
println(bools)
}
This is an attempt to show the steps of fold:
Input: 5 2 7 1 3
Output: [false, false, false, true, false]
acc value to evaluate evaluated why is f ot t added?
[] 5 [] f [f] 5 is not the minimum value
[f] 2 [f] f [f,f] 2 is not the minimum value
[f,f] 7 [f,f] f [f,f,f] 7 is not the minimum value
[f,f,f] 1 [f,f,f] t [f,f,f,t] 1 is the minimum value
[f,f,f,t,f] 3 [f,f,f,t] f [f,f,f,t,f] 4 is not the minimum value
CodePudding user response:
You can use the minOrNull
function
val elements = mutableListOf<Int>()
fun main() {
while(true) {
print("Enter a number:")
elements.add(
readLine()?.toIntOrNull() ?: break
)
val smallestElement = elements.minOrNull()
println("The smallest element in the list now is $smallestElement")
}
println("Bye bye!")
}