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. String[] data = {"a", "b", "c", "d"};
  66. int cnt = 0;
  67. StringBuilder sb = new StringBuilder();
  68. for (int[] combination : new Combinations(data.length)) {
  69. sb.setLength(0);
  70. for (int index : combination) {
  71. sb.append(data[index]);
  72. }
  73. System.out.printf("Combination %6d size %2d members %15s %8s .%n", cnt++, combination.length, Arrays.toString(combination), sb.toString());
  74. }
  75.  
  76. }
  77. }
  78.  
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
Combination      0 size  0 members              []          .
Combination      1 size  1 members             [0]        a .
Combination      2 size  1 members             [1]        b .
Combination      3 size  2 members          [0, 1]       ab .
Combination      4 size  1 members             [2]        c .
Combination      5 size  2 members          [0, 2]       ac .
Combination      6 size  2 members          [1, 2]       bc .
Combination      7 size  3 members       [0, 1, 2]      abc .
Combination      8 size  1 members             [3]        d .
Combination      9 size  2 members          [0, 3]       ad .
Combination     10 size  2 members          [1, 3]       bd .
Combination     11 size  3 members       [0, 1, 3]      abd .
Combination     12 size  2 members          [2, 3]       cd .
Combination     13 size  3 members       [0, 2, 3]      acd .
Combination     14 size  3 members       [1, 2, 3]      bcd .
Combination     15 size  4 members    [0, 1, 2, 3]     abcd .