Permutations with repetitions

Permutations are all the different orders of the elements of a set. The number of permutations is n! (n factorial), where n is the number of elements of the set. If there are repeated elements in the set to permute, the number of permutations will be smaller. I have compiled some methods in Java to obtain all the permutations with repetitions.

Contents
Introduction
Permutations with repetitions
References

Introduction

The number of permutations of a set of elements with n elements is n! (n factorial). If there are repeated elements in the set, we will have to divide by the factorial of the number of repetitions of each repeated element.

REF: "Permutaciones con repetición"

The number of permutations with repetition of n elements, with groups of k elements because of repetitions (where k = r1 + r2 + ...+ rn), written as Pkr1,r2...rn and equal to:

Pkr1,r2...rn =

n!


r1!r2! ... rn!



Permutations with repetitions

Based on the permutations generator algorithms, the following methods generate the permutations for a set with repetition:
1. The set is sorted.
2. When there are to permute, they consider if the elements are equal or no.

permutationsRep(int[]) (recursive)

/**
* Given ps, integer set with repetitions, it sorts it, and
* calls the method to permute it.
*
* @param ps Array of integers with repetitions, set of
* elements to permute.
*/
public void permutationsRep(int[] ps) {
Arrays.sort(ps);
permuteRep(ps, 0, ps.length);
}

/**
* Calls doSomething() method with all the permutations
* of the ps set.
*
* It considers when elements are repeated.
*
* Initial call: permute(ps, 0, ps.length);
*
* @param ps Array of integers with repetitions, set of
* elements to permute.
* @param start Index where permutation begins.
* @param n Number of elements of ps.
*/
public static void permute(int[] ps, int start, int n) {
doSomething(ps);
int tmp = 0;

if (start < n) {
for (int i = n - 2; i >= start; i--) {
for (int j = i + 1; j < n; j++) {
if (ps[i] != ps[j]) {
// swap ps[i] <--> ps[j]
tmp = ps[i];
ps[i] = ps[j];
ps[j] = tmp;

permute(ps, i + 1, n);
}
}

// Undo all modifications done by
// recursive calls and swapping
tmp = ps[i];
for (int k = i; k < n - 1;)
ps[k] = ps[++k];
ps[n - 1] = tmp;
}
}
}


permuteRepIteretive(int[]) (iterative)

/**
* Calls the doSomething() method with all the permutaions
* of ps.
*
* It considers when elements are repeated.
*
* @param ps Array of integers with repetitions, set of
* elements to permute.
*/
public void permuteRepIteretive(int[] ps) {
doSomething(ps);
int n = ps.length;
int tmp = 0;

// indexes[i] = i+1;
int[] indexes = new int[n];
for (int i=0; i<n-1; ) indexes[i] = ++i;

for (int i = n-2; i >= 0;) {

while(indexes[i]<n && ps[indexes[i]] == ps[i]) {
indexes[i]++;
}

// swap ps[i] <--> ps[indexes[i]
if (indexes[i]<n) {
tmp = ps[indexes[i]];
ps[indexes[i]] = ps[i];
ps[i] = tmp;

doSomething(ps);
}

indexes[i]++;

i = n-2;

while (i >= 0 && indexes[i] >= n) {
// Undo previous permutation from i+1
// Cyclical rotation to the left from i+1
// ps[k] = ps[k+1]
tmp = ps[i];
for (int k = i; k < n-1;)
ps[k] = ps[++k];
ps[n-1] = tmp;

// indexes[i]=i+1;
// i--;
indexes[i] = i-- + 1;
}
}
}


References

"Counting problems", by Johan.Claeys.
"Permutaciones con repetición".

Potencia, divide y vencerás / Exponentiation, divide and conquer

espa?olPotencia: La potencia de un número es la multiplicación de ese número por sí mismo un número determinado de veces. La potencia n de x se expresa como xn y equivale x · x · ... · x · x n veces. x0 es 1. Los siguientes métodos en Java implementan diferentes formas del cálculo de la potencia de un número.
(más)

espa?olExponentiation: The exponentiation of a number is the multiplication of that number by itself a determined number of times. Raising x to the power n is expressed like xn and is x • x • ... • x • x n times. x0 is 1. The following methods in Java implements different ways to calculate the exponentiation of a number.
(read more)

Permutaciones / Permutations

espa?ol Permutaciones: Las permutaciones son todas las distintas ordenaciones que se pueden obtener de un conjunto de elementos dados. El número de permutaciones de un conjunto dado es n! (n factorial), dónde n es el número de elementos del conjunto. El numero de permutaciones crece rápidamente con el número de elementos del conjunto, así que computacionalmente es desaconsejable en caso de conjuntos grandes, pero en ocasiones puede ser útil para conjuntos pequeños. Aquí recojo algunos métodos útiles para trabajar con permutaciones en Java.
(más)

espa?olPermutations: Permutations are all the different orders of the elements of a set. The number of permutations is n! (n factorial), where n is the number of elements of the set. The number of permutations grows quickly with the number of elements of the set, so permutations are heavy computationally, but in specific situations, they can be useful in small sets. Here I compile several useful methods related to permutations in Java.
(read more)

Palíndromos en java / Palindromes in Java

espa?olPalíndromos en Java: He actualizado el artículo dedicado a palíndromos y he añadido nuevos métodos en Java.

espa?olPalindromes in Java: I have updated the article dedicated to palindromes and I have added new methods in Java.

Nivel de bits / Bitwise tricks

espa?olTrucos a nivel de bits: Compilación de útiles e interesantes trucos a nivel de bits.

espa?olBitwise tricks: A compilation of useful and interesting bitwise tricks.

Factoriales / Factorials

espa?olFactoriales: La función factorial está muy extendida en computación y matemáticas discretas. Es una breve explicación sobre el factorial, código que puede ser útil y links interesantes relacionados con factoriales.

espa?olFactorials: The factorial function is widely used in computing and discrete Mathematics. It is a brief explanation about factorial function, useful source code and interesting links related to factorials.

Algoritmo de Boyer-Moore / Boyer-Moore Algorithm

espa?olAlgoritmo de Boyer-Moore: es el más eficiente en la búsqueda de patrones en cadenas de caracteres. Es una breve explicación del algoritmo, su código con sus pruebas y links adjuntos.

espa?olBoyer-Moore algorithm: the most efficient algorithm in pattern matching. It is a short explanation of the algorithm, its code whit its tests and attached links.

Generador de Palíndromos en Java / Java Palindromes Generator

espa?olGenerador de palíndromos numéricos: Un método en Java que genera un palíndromo numérico a partir de un número pasado como parámetro.

espa?olNumeric palindromes generator: A Java method generates a numeric palindrome from a number given.

Mi CV / My CV

espa?olLuis Javier López Arredondo, CV en inglés.
Ver mi CV

espa?olLuis Javier López Arredondo, English CV.
See my CV

Bienvenido / Welcome

españolBienvenido a mi blog.

englishWelcome to my blog.