forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.kt
37 lines (31 loc) · 1010 Bytes
/
solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.igorwojda.integer.countdown
// Kotlin idiomatic solution
private object Solution1 {
private fun countDown(n: Int): List<Int> {
// Create a range and convert it to a list
return (n downTo 0).toList()
}
}
// Recursive solution
private object Solution2 {
private fun countDown(n: Int): List<Int> {
if (n == 0) {
return listOf(0)
}
return mutableListOf(n).also { it.addAll(countDown(n - 1)) }
}
}
// Recursive solution with helper function
private object Solution3 {
private fun countDown(n: Int): List<Int> {
// We want to keep return type unchanged while implementing recursive solution, so we will
// use helper method defied inside countDown function.
fun helper(n: Int): MutableList<Int> {
if (n == 0) {
return mutableListOf(0)
}
return mutableListOf(n).also { it.addAll(countDown(n - 1)) }
}
return helper(n).toList()
}
}