Skip to content

Commit 4eae3ba

Browse files
committed
added initial Kotlin puzzlers
1 parent a4ee52e commit 4eae3ba

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package org.kotlin.examples
2+
3+
import org.junit.Test
4+
import kotlin.test.assertEquals
5+
import kotlin.test.assertNull
6+
import kotlin.test.assertTrue
7+
8+
/**
9+
* To look at
10+
* https://github.com/angryziber/kotlin-puzzlers
11+
*/
12+
class PuzzlesTest {
13+
14+
enum class E { e }
15+
16+
@Test
17+
fun exhaustiveEnum() {
18+
val en = E.e
19+
val a = when (E.e) {
20+
en -> "1" // will be known at the runtime so else/other branches should be covered
21+
PuzzlesTest.E.e -> "2"
22+
}
23+
assertEquals("1", a)
24+
}
25+
26+
//ClosedRange.contains() converts parameter into Int before checking
27+
@Test
28+
fun inclusiveRange() {
29+
val i = 10.5
30+
var res = ""
31+
when (i) {
32+
in 1..10 -> res = "in"
33+
!in 1..10 -> res = "!in"
34+
else -> res = "else"
35+
}
36+
assertEquals("in", res)
37+
}
38+
39+
@Test
40+
fun eagerOrLazy() {
41+
//eager
42+
val x = listOf(1, 2, 3).filter { print("$it "); it >= 2 }
43+
println()
44+
assertEquals(5, x.sum())
45+
// lazy
46+
val y = sequenceOf(1, 2, 3).filter { print("$it "); it >= 2 }
47+
println()
48+
assertEquals(5, y.sum())
49+
// or
50+
val z = listOf(1, 2, 3).asSequence().filter { print("$it "); it >= 2 }
51+
println()
52+
assertEquals(5, z.sum())
53+
}
54+
55+
@Test(expected = UnsupportedOperationException::class)
56+
fun isMutable() {
57+
val readonly = listOf(1, 2, 3)
58+
59+
if (readonly is MutableList) {
60+
readonly.add(4)
61+
}
62+
63+
assertEquals(readonly, listOf(1,2,3))
64+
}
65+
66+
@Test
67+
fun inclusiveRanges() {
68+
val range = 0..9 step 3
69+
70+
assertEquals("0, 3, 6, 9", range.joinToString())
71+
}
72+
73+
@Test
74+
fun mapWithDefault() {
75+
val map = mapOf<Any, Any>().withDefault{ "default" }
76+
assertNull(map["1"])
77+
}
78+
79+
@Test
80+
fun reversedRanges() {
81+
val range = 0..10
82+
83+
val reverseThenStep = range.reversed().step(3).toList()
84+
val stepThenReverse = range.step(3).reversed().toList()
85+
86+
assertEquals(listOf(10, 7, 4, 1), reverseThenStep)
87+
assertEquals(listOf(9, 6, 3, 0), stepThenReverse)
88+
}
89+
90+
@Test
91+
fun sorted() {
92+
val list = arrayListOf(1, 5, 3, 2, 4)
93+
94+
val sortedList = list.sort()
95+
96+
assertTrue(sortedList is kotlin.Unit)
97+
}
98+
}

0 commit comments

Comments
 (0)