Skip to content

Instantly share code, notes, and snippets.

@IngeFrodo
Created August 14, 2020 03:11
Show Gist options
  • Save IngeFrodo/9156a427815dcf9340bb55c14e2a2360 to your computer and use it in GitHub Desktop.
Save IngeFrodo/9156a427815dcf9340bb55c14e2a2360 to your computer and use it in GitHub Desktop.
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