Combinatorial Analysis - Generate n! arrangements

0

I need an algorithm that manages all possible arrangements for n elements in n positions, that is, n! 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';
    }
}
    
asked by anonymous 22.01.2018 / 16:55

1 answer

2

My response was inspired by this post , if you wanted more explanation.

I used three functions to get 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 its case is n and will mount an array with all values from 1 to n . At the end it will call the function permutacao_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 one, 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 is enough to declare a global variable

var lista = [];

and call the function buld_char(3); passing the value of n

    
22.01.2018 / 18:28