How to iteratively generate k elements subsets from a set of size n in java?

后端 未结 7 1802
忘掉有多难
忘掉有多难 2020-11-29 09:14

I\'m working on a puzzle that involves analyzing all size k subsets and figuring out which one is optimal. I wrote a solution that works when the number of subsets is small,

7条回答
  •  生来不讨喜
    2020-11-29 09:45

    Here is a combination iterator I wrote recetnly

    package psychicpoker;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    
    import static com.google.common.base.Preconditions.checkArgument;
    
    public class CombinationIterator implements Iterator> {
    
    private int[] indices;
    private List elements;
    private boolean hasNext = true;
    
    public CombinationIterator(List elements, int k) throws IllegalArgumentException {
        checkArgument(k<=elements.size(), "Impossible to select %d elements from hand of size %d", k, elements.size());
        this.indices = new int[k];
        for(int i=0; i next() {
        Collection result = new ArrayList(indices.length);
        for(int i=indices.length-1; i>=0; i--) {
            result.add(elements.get(indices[i]));
        }
        hasNext = inc();
        return result;
    }
    
    public void remove() {
        throw new UnsupportedOperationException();
    }
    

    }

提交回复
热议问题