0
0
Kotlinprogramming~20 mins

Generating infinite sequences in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Infinite Sequence Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple infinite sequence with take
What is the output of this Kotlin code snippet?
Kotlin
val seq = generateSequence(1) { it + 2 }
println(seq.take(5).toList())
A[1, 4, 7, 10, 13]
B[2, 4, 6, 8, 10]
C[1, 2, 3, 4, 5]
D[1, 3, 5, 7, 9]
Attempts:
2 left
💡 Hint
Look at how the sequence starts and how the lambda adds 2 each time.
🧠 Conceptual
intermediate
1:30remaining
Understanding termination of infinite sequences
Which statement about Kotlin infinite sequences is true?
AInfinite sequences in Kotlin are stored fully in memory.
BAn infinite sequence always runs forever and cannot be limited.
CYou can limit an infinite sequence by using terminal operations like take or first.
DYou must convert an infinite sequence to a list before using it.
Attempts:
2 left
💡 Hint
Think about how you can get a finite result from an infinite source.
Predict Output
advanced
2:30remaining
Output of a Fibonacci infinite sequence
What is the output of this Kotlin code?
Kotlin
val fibs = generateSequence(Pair(0, 1)) { Pair(it.second, it.first + it.second) }
println(fibs.take(7).map { it.first }.toList())
A[0, 1, 1, 2, 3, 5, 8]
B[1, 1, 2, 3, 5, 8, 13]
C[0, 1, 2, 3, 5, 8, 13]
D[1, 2, 3, 5, 8, 13, 21]
Attempts:
2 left
💡 Hint
The sequence generates pairs where the first is the current Fibonacci number.
Predict Output
advanced
2:00remaining
Terminating a sequence with null
What is the output of this Kotlin code?
Kotlin
val seq = generateSequence(1) { if (it < 5) it + 1 else null }
println(seq.toList())
A[1, 2, 3, 4, 5]
BThrows IllegalStateException due to null in sequence
C[1, 2, 3, 4]
DThrows NullPointerException
Attempts:
2 left
💡 Hint
Check what happens when the lambda returns null.
📝 Syntax
expert
2:30remaining
Which option produces a valid infinite sequence of powers of 2?
Select the Kotlin code snippet that correctly generates an infinite sequence of powers of 2 starting at 1.
Aval seq = generateSequence(1) { it + it }
Bval seq = generateSequence(1) { it * 2 }
Cval seq = generateSequence(1) { it xor 2 }
Dval seq = generateSequence(1) { it ** 2 }
Attempts:
2 left
💡 Hint
Check Kotlin operators for multiplication and exponentiation.