1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

problems: add „1286. Iterator for Combination“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-08-09 15:14:12 +02:00
parent 234ae9fcf2
commit dd3b626157
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,46 @@
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()
*/