fork(1) download
  1. /* package whatever; // don't place package name! */
  2. import java.util.Arrays;
  3. import java.util.Iterator;
  4. import java.util.NoSuchElementException;
  5.  
  6.  
  7.  
  8. @SuppressWarnings("javadoc")
  9. class Combinations implements Iterable<int[]> {
  10.  
  11. private class Yielder implements Iterator<int[]> {
  12. private final long size;
  13. private final long limit;
  14. private long next = 0;
  15. private final int[] stash;
  16.  
  17. public Yielder(int size) {
  18. super();
  19. this.size = size;
  20. this.limit = 1 << size;
  21. this.stash = new int[size];
  22. }
  23. @Override
  24. public boolean hasNext() {
  25. return next < limit;
  26. }
  27. @Override
  28. public int[] next() {
  29. if (next >= limit) {
  30. }
  31. int count = 0;
  32. for (int b = 0; b < size; b++) {
  33. if ((next & (1 << b)) != 0) {
  34. stash[count++] = b;
  35. }
  36. }
  37. next++;
  38. return Arrays.copyOf(stash, count);
  39. }
  40. @Override
  41. public void remove() {
  42. }
  43.  
  44. }
  45.  
  46. private final int datasize;
  47.  
  48. /**
  49.   * @param datasize
  50.   */
  51. public Combinations(int datasize) {
  52. super();
  53. this.datasize = datasize;
  54. }
  55.  
  56. @Override
  57. public Iterator<int[]> iterator() {
  58. return new Yielder(datasize);
  59. }
  60.  
  61.  
  62.  
  63. public static void main(String[] args) {
  64.  
  65. int cnt = 0;
  66. for (int[] combination : new Combinations(3)) {
  67. System.out.printf("Combination %6d size %2d members %s.%n", cnt++, combination.length, Arrays.toString(combination));
  68. }
  69.  
  70. }
  71. }
  72.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Combination      0 size  0 members [].
Combination      1 size  1 members [0].
Combination      2 size  1 members [1].
Combination      3 size  2 members [0, 1].
Combination      4 size  1 members [2].
Combination      5 size  2 members [0, 2].
Combination      6 size  2 members [1, 2].
Combination      7 size  3 members [0, 1, 2].