PermutationGenerator.java

/*
 * Copyright (C) 2019 sw4j.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.sw4j.tool.p12breaker.permutation;

import java.util.concurrent.BlockingQueue;

/**
 *
 * @author Uwe Plonus
 */
public class PermutationGenerator {

    private final PermutationConfiguration config;

    private final BlockingQueue<String> emitter;

    public PermutationGenerator(final PermutationConfiguration config, final BlockingQueue<String> emitter) {
        this.config = config;
        this.emitter = emitter;
    }

    public void createPermutations() throws InterruptedException {
        String permutationString = config.getPermutationString();
        for (int length = config.getMinimumLength(); length <= config.getMaximumLength(); length++) {
            int[] currentChar = new int[length];
            boolean lengthDone = false;
            while (!lengthDone) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length; i++) {
                    sb.insert(0, permutationString.charAt(currentChar[i]));
                }
                emitter.put(sb.toString());
                boolean carry = true;
                for (int i = 0; i < length; i++) {
                    if (carry) {
                        carry = false;
                        currentChar[i]++;
                        if (currentChar[i] >= permutationString.length()) {
                            carry = true;
                            currentChar[i] = 0;
                            if (i >= length - 1) {
                                lengthDone = true;
                            }
                        }
                    }
                }
            }
        }
    }

}