1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/kt/iterator-for-combination.kt
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +02: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()
*/