1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/kt/iterator-for-combination.kt
Matej Focko aaaebf1d52
style(kt): reformat the files
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-05-17 18:23:38 +02:00

44 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()
*/