From dd3b62615792ecad5ccd34292227d14eb85869f6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 9 Aug 2022 15:14:12 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E1286.=20Iterator=20f?= =?UTF-8?q?or=20Combination=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/iterator-for-combination.kt | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 problems/iterator-for-combination.kt diff --git a/problems/iterator-for-combination.kt b/problems/iterator-for-combination.kt new file mode 100644 index 0000000..3214114 --- /dev/null +++ b/problems/iterator-for-combination.kt @@ -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() + */