A.
Appendix A: Chapter 1 Exercise Solutions
Written by Massimo Carli
Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as
text.
Exercise 1.1
Implement the function sumInRange
that sums the values in a List<String>
within a given interval. The signature is:
fun sumInRange(input: List<String>, range: IntRange): Int
Exercise 1.1 solution
A possible solution is the following:
fun sumInRange(input: List<String>, range: IntRange): Int = // 1
input
.filter(::isValidNumber) // 2
.map(String::toInt) // 3
.filter { it in range } // 4
.sum() // 5
fun main() {
println(sumInRange(listOf("1", "10", "a", "7", "ad2", "3"), 1..5))
}
4
Exercise 1.2
Implement chrono
, which accepts a function of type () -> Unit
as input and returns the time spent to run it. The signature is:
fun chrono(fn: () -> Unit): Long
Exercise 1.2 solution
A possible implementation for chrono
is the following:
fun chrono(fn: () -> Unit): Long { // 1
val start = System.currentTimeMillis() // 2
fn() // 3
return System.currentTimeMillis() - start // 4
}
fun main() {
val waitOneSec = { Thread.sleep(1000) } // 1
println(chrono(waitOneSec)) // 2
}
1005