Combinatorial Analysis - Generate n! arrangements

Asked

Viewed 842 times

0

I need an algorithm that manages all possible arrangements for n elements in n positions, that is to say, 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';
    }
}

1 answer

1


My response was inspired by this post, case you want further explanations.

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 your case is n and will mount an array of 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, which will swap the array characters

function troca_char(str, p1, p2) {
    aux = str[p1];
    str[p1] = str[p2]
    str[p2] = aux;
    return str;
}

Having these three functions it is sufficient to declare a global variable

var lista = [];

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

  • I don’t think the global is necessary. From what I understand, it could very well be build_char

Browser other questions tagged

You are not signed in. Login or sign up in order to post.