forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.kt
47 lines (37 loc) · 1 KB
/
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
38
39
40
41
42
43
44
45
46
47
package com.igorwojda.integer.getodd
// Kotlin idiomatic solution
private object Solution1 {
private fun filterOdd(list: List<Int>): List<Int> {
return list.filter { it % 2 == 1 }
}
}
// Recursive solution
private object Solution2 {
private fun filterOdd(list: List<Int>): List<Int> {
if (list.isEmpty()) {
return list
}
return if (list.first() % 2 == 1) {
mutableListOf(list.first()) + filterOdd(list.drop(1))
} else {
filterOdd(list.drop(1))
}
}
}
// Recursive solution with helper function
private object Solution3 {
private fun filterOdd(list: List<Int>): List<Int> {
val result = mutableListOf<Int>()
fun helper(list: List<Int>) {
if (list.isEmpty()) {
return
}
if (list.first() % 2 == 1) {
result.add(list.first())
}
helper(list.drop(1))
}
helper(list)
return result
}
}