Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. public class CombinationsGenerator implements Iterator {
  2. private int n, k;
  3. private int[] array;
  4.  
  5. public CombinationsGenerator(int n, int k) {
  6. this.n = n;
  7. this.k = k;
  8.  
  9. array = new int[k];
  10.  
  11. for (int i = 0; i < k; i++)
  12. array[i] = n - i;
  13. array[k - 1]++; // Fix for the first next() call
  14. }
  15.  
  16. @Override
  17. public boolean hasNext() {
  18. return array[0] > k;
  19. }
  20.  
  21. @Override
  22. public int[] next() {
  23. for (int i = k - 1; i >= 0; i--) {
  24. if (array[i] > k - i - 1) {
  25. array[i]--;
  26. for (int j = i + 1; j < k; j++) {
  27. array[j] = array[j - 1] - 1;
  28. }
  29. break;
  30. }
  31. }
  32.  
  33. return array;
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement