LeetCode/kt/iterator-for-combination.kt
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

46 lines
1.3 KiB
Kotlin

class CombinationIterator(val characters: String, val combinationLength: Int) {
private var indices = (0 until combinationLength).toMutableList()
private fun nextCombination(index: Int) {
// bump the current index
indices[index]++
// we have gone through the whole string
while (indices[index] == characters.length && index > 0) {
// bump the previous index
nextCombination(index - 1)
// set current index to previous + 1, since it must be the following one
indices[index] = indices[index - 1] + 1
}
}
// By default bumping just the last index
private fun nextCombination() = nextCombination(combinationLength - 1)
private fun getCombination(): String =
indices.map { characters[it] }.joinToString(separator="")
fun next(): String {
// construct the combination
val combination = getCombination()
// bump the combination
nextCombination()
return combination
}
fun hasNext(): Boolean =
indices.all {
it < characters.length
}
}
/**
* Your CombinationIterator object will be instantiated and called as such:
* var obj = CombinationIterator(characters, combinationLength)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/