0
0
Kotlinprogramming~10 mins

Fold and reduce operations in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the sum of all numbers in the list using fold.

Kotlin
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.fold([1]) { acc, num -> acc + num }
println(sum)
Drag options to blanks, or click blank then click option'
A0
B1
Cnull
D""
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as initial value will add 1 extra to the sum.
Using null causes a runtime error.
2fill in blank
medium

Complete the code to find the product of all numbers in the list using reduce.

Kotlin
val numbers = listOf(2, 3, 4)
val product = numbers.reduce { acc, num -> acc [1] num }
println(product)
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' will sum instead of multiply.
Using '-' or '/' will give wrong results or errors.
3fill in blank
hard

Fix the error in the code to correctly concatenate all strings in the list using fold.

Kotlin
val words = listOf("Kotlin", "is", "fun")
val sentence = words.fold([1]) { acc, word -> acc + " " + word }
println(sentence.trim())
Drag options to blanks, or click blank then click option'
A1
B""
C0
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using null causes a NullPointerException.
Using 0 or 1 causes type mismatch errors.
4fill in blank
hard

Fill both blanks to create a map of words to their lengths, but only include words longer than 3 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val lengths = words.associateWith { [1] }
val filtered = lengths.filter { it.value [2] 3 }
println(filtered)
Drag options to blanks, or click blank then click option'
Ait.length
B>
C<
Dit.size
Attempts:
3 left
💡 Hint
Common Mistakes
Using it.size is invalid for String.
Using '<' filters shorter words, not longer.
5fill in blank
hard

Fill all three blanks to create a map of uppercase words to their lengths, including only words longer than 4 characters.

Kotlin
val words = listOf("tree", "house", "car", "elephant")
val result = words.filter { it.length [1] 4 }
    .associateBy([2]) { [3] }
println(result)
Drag options to blanks, or click blank then click option'
A>
Bit.uppercase()
Cit.length
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters shorter words.
Using it.lowercase() instead of uppercase.
Swapping key and value in associateBy.