Testing Collection Rules
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 33 of 63.
any asks whether at least one element matches, all whether every element matches, and none whether no element matches. For an empty input, any is false, while all and none are true. These operations return one Boolean, not a filtered collection.
Inside main:
val values = emptyList<Int>()
println(values.all { it > 0 })There is no element that violates the rule, so all returns true for the empty list.
On an empty collection, any is false while all and none are true.
Challenge
MediumComplete hasNegative with parameters values: List<Int>. Return whether at least one value is negative. Use any.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type Boolean. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun hasNegative(values: List<Int>): Boolean {
// Write your solution here.
return false
}
fun main() {
val valuesCount = readln().toInt()
val values = mutableListOf<Int>()
for (i0 in 0 until valuesCount) {
val valuesItem = readln().toInt()
values.add(valuesItem)
}
println(hasNegative(values))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind ContactsPractice on your own: Kotlin playground