/*
  This file is part of the BJP package.

  BJP package is free software: you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation, either version 3 of the License, or (at your
  option) any later version.

  BJP package 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 Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with BJP package.  If not, see <http://www.gnu.org/licenses/>.
 */
package util.math;

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

/**
 * Simple class for computing the permutations of a set of variables with
 * discrete cardinalities
 * 
 * @author fschluter
 */
public class Permutations {
	private static List<int[]> permutations;

	/**
	 * @param x
	 * @param cardinalities
	 * @return
	 */
	public static List<int[]> getPermutations(List<Integer> x, int[] cardinalities) {
		permutations = new ArrayList<int[]>();
		int[] n = new int[x.size()];
		int[] cards = new int[x.size()];

		for (int i = 0; i < x.size(); ++i) {
			cards[i] = cardinalities[x.get(i)];
		}

		getPermutationsRecursively(n, cardinalities, 0);
		return permutations;
	}

	/**
	 * @param vars
	 * @param cardinalities
	 * @param idx
	 */
	private static void getPermutationsRecursively(int[] vars, int[] cardinalities, int idx) {
		int[] variables = new int[vars.length];
		System.arraycopy(vars, 0, variables, 0, vars.length);

		/* stop condition for the recursion [base clause] */
		if (idx == variables.length) {
			permutations.add(variables);
			return;
		}
		for (int i = 0; i < cardinalities[idx]; i++) {
			variables[idx] = i;
			/* recursive invocation, for next elements */
			getPermutationsRecursively(variables, cardinalities, idx + 1);

		}
	}


	
}
