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