Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

algorithm - Creating Combinations in JavaScript

Lets say I have several sets of options in Javascript

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];

what is an efficient algorithm to get all the combinations of these options in an array that looks like this

["red and small and heavy", "red and small and light", "red and medium and heavy" ...]

Here's the caveat though

This function must be able to take any number of sets of options

I have a feeling that the proper way to do this is through some sort of tree traversal, but its too early to have fully thought this through and I haven't had my coffee yet

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function permutations(choices, callback, prefix) {
    if(!choices.length) {
        return callback(prefix);
    }
    for(var c = 0; c < choices[0].length; c++) {
        permutations(choices.slice(1), callback, (prefix || []).concat(choices[0][c]));
    }
}

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];

permutations([color, size, weight], console.log.bind(console));

Seems to work...

[ 'red', 'small', 'heavy' ]
[ 'red', 'small', 'light' ]
[ 'red', 'medium', 'heavy' ]
[ 'red', 'medium', 'light' ]
[ 'red', 'large', 'heavy' ]
[ 'red', 'large', 'light' ]
[ 'blue', 'small', 'heavy' ]
[ 'blue', 'small', 'light' ]
[ 'blue', 'medium', 'heavy' ]
[ 'blue', 'medium', 'light' ]
[ 'blue', 'large', 'heavy' ]
[ 'blue', 'large', 'light' ]
[ 'green', 'small', 'heavy' ]
[ 'green', 'small', 'light' ]
[ 'green', 'medium', 'heavy' ]
[ 'green', 'medium', 'light' ]
[ 'green', 'large', 'heavy' ]
[ 'green', 'large', 'light' ]
[ 'yellow', 'small', 'heavy' ]
[ 'yellow', 'small', 'light' ]
[ 'yellow', 'medium', 'heavy' ]
[ 'yellow', 'medium', 'light' ]
[ 'yellow', 'large', 'heavy' ]
[ 'yellow', 'large', 'light' ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...