git @ Cat's Eye Technologies Dipple / master javascript / all-permutations.js
master

Tree @master (Download .tar.gz)

all-permutations.js @masterraw · history · blame

// SPDX-FileCopyrightText: Chris Pressey, the original author of this work, has dedicated it to the public domain.
// For more information, please refer to <https://unlicense.org/>
// SPDX-License-Identifier: Unlicense

function allPermutations(items) {
    var item;
    var subItems;
    var permutations = [];
    for (var i = 0; i < items.length; i++) {
        item = items[i];
        subItems = items.slice();
        subItems.splice(i, 1);
        if (subItems.length > 0) {
            var subPermutations = allPermutations(subItems);
            for (var j = 0; j < subPermutations.length; j++) {
                var newItems = [item].concat(subPermutations[j]);
                permutations.push(newItems);
            }
        } else {
            permutations.push([item]);
        }
    }
    return permutations;
}