All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.paukov.combinatorics3.SimplePermutationIterator Maven / Gradle / Ivy

Go to download

Simple java library to generate permutations, combinations and other combinatorial sequences

There is a newer version: 3.4.0
Show newest version
/**
 * Combinatorics Library 3
 * Copyright 2016 Dmytro Paukov [email protected]
 */
package org.paukov.combinatorics3;

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


/**
 * Iterator for the permutation generator
 *
 * @author Dmytro Paukov
 * @version 3.0
 * @see SimplePermutationGenerator
 * @param 
 *            Type of elements in the permutations
 */
class SimplePermutationIterator implements Iterator> {

    final SimplePermutationGenerator _generator;
    final List _currentPermutation;
    final int _length;
    long _currentIndex = 0;

    private int[] _pZ = null;
    private int[] _pP = null;
    private int[] _pD = null;
    private int m = 0;
    private int w = 0;
    private int pm = 0;
    private int dm = 0;
    private int zpm = 0;

    SimplePermutationIterator(SimplePermutationGenerator generator) {
        _generator = generator;
        _length = generator._originalVector.size();
        _currentPermutation = new ArrayList<>(generator._originalVector);
        _pZ = new int[_length + 2];
        _pP = new int[_length + 2];
        _pD = new int[_length + 2];

        _currentIndex = 0;

        m = 0;
        w = 0;
        pm = 0;
        dm = 0;
        zpm = 0;

        for (int i = 1; i <= _length; i++) {
            _pP[i] = i;
            _pZ[i] = i;
            _pD[i] = -1;
        }
        _pD[1] = 0;
        _pZ[_length + 1] = m = _length + 1;
        _pZ[0] = _pZ[_length + 1];

    }


    @Override
    public boolean hasNext() {
        return m != 1;
    }


    @Override
    public List next() {

        for (int i = 1; i <= _length; i++) {
            int index = _pZ[i] - 1;
            _currentPermutation.set(i-1, _generator._originalVector.get(index));
        }
        m = _length;
        while (_pZ[_pP[m] + _pD[m]] > m) {
            _pD[m] = -_pD[m];
            m--;
        }
        pm = _pP[m];
        dm = pm + _pD[m];
        w = _pZ[pm];
        _pZ[pm] = _pZ[dm];
        _pZ[dm] = w;
        zpm = _pZ[pm];
        w = _pP[zpm];
        _pP[zpm] = pm;
        _pP[m] = w;
        _currentIndex++;

        return new ArrayList<>(_currentPermutation);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }


    @Override
    public String toString() {
        return "PermutationIterator=[#" + _currentIndex + ", "
                + _currentPermutation + "]";
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy