wegner.michael.micksutils.combinatorics.CombinationsIterator.java Source code

Java tutorial

Introduction

Here is the source code for wegner.michael.micksutils.combinatorics.CombinationsIterator.java

Source

/*******************************************************************************
* Copyright (c) 2014 ETAS GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Dennis Eder (ETAS GmbH) - initial API and implementation and/or initial documentation
*******************************************************************************/
package wegner.michael.micksutils.combinatorics;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.math3.util.Combinations;

public class CombinationsIterator<T> implements Iterator<List<T>> {
    protected List<T> input;
    Iterator<int[]> numericCore;

    /**
     * 
     * @param input
     *            - list of elements to be combined
     * @throws Exception
     */
    public CombinationsIterator(List<T> input) throws Exception {
        this(input, input.size());
    }

    /**
     * 
     * @param input
     *            - list of elements to be k-combined
     * @param k
     *            - parameter of k-combinations
     * @throws Exception
     */
    public CombinationsIterator(List<T> input, int k) throws Exception {
        this.input = input;
        numericCore = new Combinations(input.size(), k).iterator();
    }

    @Override
    public boolean hasNext() {
        return numericCore.hasNext();
    }

    @Override
    public List<T> next() {
        int[] indices = numericCore.next();
        ArrayList<T> res = new ArrayList<>();
        for (int index : indices) {
            res.add(input.get(index));
        }
        return res;
    }
}