Created
March 13, 2021 08:21
-
-
Save joost-de-vries/74cae109951d69d53870a5996ba0b09a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Test | |
import kotlin.test.assertEquals | |
class Interview { | |
val input = "aaaabbbcca" | |
val expectedOutput = listOf('a' to 4, 'b' to 3, 'c' to 2, 'a' to 1) | |
@Test | |
fun `interview - fold`() { | |
val output = input.fold(listOf<Pair<Char, Int>>()) { acc, c -> acc.inc(c) } | |
assertEquals(expectedOutput, output) | |
} | |
fun List<Pair<Char, Int>>.inc(c: Char): List<Pair<Char, Int>> { | |
val prev = lastOrNull().takeIf { it?.first == c } | |
return when { | |
size == 0 -> this + (c to 1) | |
prev == null -> this + (c to 1) | |
else -> this.dropLast(1) + (c to prev.second + 1) | |
} | |
} | |
@Test | |
fun `interview - fold plus`() { | |
val output = input.fold(listOf<Pair<Char, Int>>()) { acc, c -> acc + c } | |
assertEquals(expectedOutput, output) | |
} | |
operator fun List<Pair<Char, Int>>.plus(c: Char): List<Pair<Char, Int>> = | |
inc(c) | |
@Test | |
fun `interview tailrec`() { | |
val output = listOf<Pair<Char, Int>>().count(input) | |
assertEquals(expectedOutput, output) | |
} | |
tailrec fun List<Pair<Char, Int>>.count(remaining: String): List<Pair<Char, Int>> = | |
when (val c = remaining.firstOrNull()) { | |
null -> this | |
else -> inc(c).count(remaining.drop(1)) | |
} | |
@Test | |
fun `interview mutable`() { | |
val output = countMutable(input) | |
assertEquals(expectedOutput, output) | |
} | |
fun countMutable(input: String): List<Pair<Char, Int>> { | |
var accumulator = emptyList<Pair<Char, Int>>() | |
for (c in input) { | |
accumulator = accumulator.inc(c) | |
} | |
return accumulator | |
} | |
fun countMutable2(input: String): List<Pair<Char, Int>> { | |
var accumulator = emptyList<Pair<Char, Int>>() | |
for (c in input) { | |
accumulator += c | |
} | |
return accumulator | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment