Combinatory Analysis - Generate n! arrangements
-
I need an algorithm that manages all possible arrangements for n elements n positions, that is, No! is the amount of possible arrangements, as in the example below:
n = 3 3! = 6 arranjos
123
132
213
231
312
321
I'm trying to create it in JavaScript, but it's not working.
function partida(){
var nc = 4;
var nl = fatorial(nc);var jogada = new Array(nl); for (i = 0; i < nl; i++){ jogada[i] = new Array(nc); } for (c = 0; c < nc; c++){ var q = fatorial(nc - c)/(nc - c); for (l = 0; l < nl; l++){ jogada[l][c] = Math.trunc(l/q) + c; } } textarea = document.getElementById('arranjos'); for (l = 0; l < nl; l++){ textarea.innerHTML += (jogada[l].toString()).replace(/,/g, ""); textarea.innerHTML += '\n'; }
}
-
My response was inspired by this http://marmsx.msxall.com/cursos/c16.html If you want more explanations.
I used three functions to get to the answer.
function buld_char(valor){ for (var i = 0; i < valor; i++) { lista.push(i+1); } permutacao_recursiva(lista,0); }
This function will receive a value, which in your case is
n
and will mount an array with all values from 1 ton
. At the end he will call the functionpermutacao_recursiva()
;function permutacao_recursiva(str,k){ var i, len; len = str.length;
if (k == len) console.log(str); else { for (i = k; i < len; i++) { str = troca_char(str, k, i); permutacao_recursiva(str, k + 1); str = troca_char(str, i, k); } }
}
Whenever necessary this function will call a third, which will change the characters of the array
function troca_char(str, p1, p2) {
aux = str[p1];
str[p1] = str[p2]
str[p2] = aux;
return str;
}
Having these three functions just declare a global variable
var lista = [];
and call function
buld_char(3);
passing the value ofn