language: Java (sun-jdk-1.7.0_10)
date: 626 days 4 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
 
class Main {
    public static void main(String[] args) {
        int[][] limits = {
                { 5, 7 },   // first  variable ranges from 5 to 7
                { 1, 3 }    // second variable ranges from 1 to 3
        };
        
        CombinationIterator iter = new CombinationIterator(limits);
        
        while (iter.hasNext())
            System.out.println(Arrays.toString(iter.next()));
    }
}
 
class CombinationIterator implements Iterator<int[]> {
    
    int[][] limits;
    int[] current;
    
    public CombinationIterator(int[][] limits) {
        this.limits = limits;
        
        // Initialize all variables to their minimums.
        current = new int[limits.length];
        for (int i = 0; i < limits.length; i++)
            current[i] = limits[i][0];
    }
    
    @Override
    public boolean hasNext() {
        return current != null;
    }
    
    @Override
    public int[] next() {
        
        if (current == null)
            throw new IllegalStateException("No more combinations.");
        
        int[] toReturn = current.clone();
        
        for (int i = limits.length - 1; i >= -1; i--) {
            if (i == -1) {
                current = null;
                break;
            } if (current[i] < limits[i][1]) {
                current[i]++;
                break;
            } else
                current[i] = limits[i][0];
        }
        
        return toReturn;
    }
 
    @Override
    public void remove() {
        throw new UnsupportedOperationException("Can't remove combinations");
    }
}