Skip to content Skip to sidebar Skip to footer

Javascript /jquery : How To Get Permutations From Items Of An Array?

If I have one array that contains items , for example ['To','Ti','Ta'] I would like to have a function that return all permutations of appended items in array, here function wou

Solution 1:

What you are looking for are permutations. You can create them with a recursive function.

The code below is an example. permute is the front-end function, which your code should call. permute_rec is the recursive function that builds the permutation array and swap is just a convenience function for swapping elements in an array:

functionswap(array, i, j) {
    if (i != j) {
        var swap = array[i];
        array[i] = array[j];
        array[j] = swap;
    }
}

functionpermute_rec(res, str, array) {
    if (array.length == 0) {
        res.push(str);
    } else {
        for (var i = 0; i < array.length; i++) {
            swap(array, 0, i);
            permute_rec(res, str + array[0], array.slice(1));
            swap(array, 0, i);
        }
    }
}

functionpermute(array) {
    var res = [];

    permute_rec(res, "", array);
    return res;
}

console.log(permute(["A", "B", "C"]));

Edit: You can extend this code to include permutations of subarrays with this code:

function xpermute_rec(res, sub, array) {
    if (array.length == 0) {
        if (sub.length > 0) permute_rec(res, "", sub);
    } else {
        xpermute_rec(res, sub, array.slice(1));
        xpermute_rec(res, sub.concat(array[0]), array.slice(1));
    }
}

function xpermute(array) {
    var res = [];

    xpermute_rec(res, [], array);
    return res;
}

console.log(xpermute(["A", "B", "C"]));

This code creates all subarrays and then uses the original code to create the permutations. (The case of the empty array is skipped.)

Post a Comment for "Javascript /jquery : How To Get Permutations From Items Of An Array?"