robstoll
03/21/2018, 4:22 PMval list = mutableListOf()
var parent = map[current]
while(parent != null){
list.add(parent)
parent = map[parent]
}
I have the feeling there is a functional equivalent but I cannot come up with what it isAndreas Sinz
03/21/2018, 4:24 PMrobstoll
03/21/2018, 4:25 PMrobstoll
03/21/2018, 4:26 PMAndreas Sinz
03/21/2018, 4:26 PMAndreas Sinz
03/21/2018, 4:26 PMrobstoll
03/21/2018, 4:27 PMAndreas Sinz
03/21/2018, 4:28 PMwhile
-loop way: https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functionsrobstoll
03/21/2018, 4:29 PMrobstoll
03/21/2018, 4:29 PMdsavvinov
03/21/2018, 4:48 PMgenerateSequence
would fit nicely here:
fun main(args: Array<String>) {
val initial = 0
val map: Map<Int, Int?> = mapOf(
0 to 2,
2 to 1,
1 to 3,
3 to null
)
generateSequence(initial) { map[it] }.toList()
}
Code above prints [0, 2, 1, 3]
robstoll
03/21/2018, 4:58 PMrobstoll
03/21/2018, 4:59 PMdiesieben07
03/21/2018, 4:59 PMrobstoll
03/21/2018, 4:59 PMrobstoll
03/21/2018, 5:07 PMdsavvinov
03/21/2018, 5:13 PMGeneratorSequence
), then takes iterator from it (which will just delegate to passed function along with some simple conditional checks) and uses it to iterate over sequence in a usual way.
Overhead shouldn't be very significant, unless you absolutely need every bit of a performance -- in such case yes, you will have to sacrifice code conciseness and readability for performance (which is extremely rare case, tbh)robstoll
03/21/2018, 5:22 PMrobstoll
03/21/2018, 5:27 PMrobstoll
03/21/2018, 5:27 PMrobstoll
03/21/2018, 5:29 PM