Created
August 14, 2020 03:11
-
-
Save IngeFrodo/9156a427815dcf9340bb55c14e2a2360 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CombinationIterator { | |
private Queue<String> queue; | |
public CombinationIterator(String characters, int combinationLength) { | |
queue = new LinkedList<>(); | |
generateCombinations(new char[combinationLength], 0, | |
characters.toCharArray(), 0, combinationLength, queue); | |
} | |
public String next() { | |
return queue.poll(); | |
} | |
public boolean hasNext() { | |
return !queue.isEmpty(); | |
} | |
private void generateCombinations(char[] chars, int index, char[] base, int start, int len, Queue<String> combinations) { | |
if (index == len) { | |
combinations.offer(new String(chars, 0, len)); | |
return; | |
} | |
for (int i = start; i < base.length; i++) { | |
chars[index++] = base[i]; | |
generateCombinations(chars, index, base, i + 1, len, combinations); | |
index--; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment