在JavaScript创建组合组合、JavaScript

2023-09-11 06:17:57 作者:霸气的女人最有范er

可以说我有几套方案在Javascript

  VAR颜色=红,蓝,绿,黄];
VAR大小= [小,中等,大];
VAR体重= [重,轻];
 

什么是有效的算法来获得这些选项的所有组合在一个数组看起来像这样

  [红色小而重,红色小而轻,红,中型和重型...]
 

这里的警告,虽然

此功能必须能够采取任何多套方案

我有一种感觉,正确的方法做,这是通过某种树的遍历,但它的太早已经充分想到这通过,我还没有我的咖啡又

解决方案

 函数组合(选择,回调,preFIX){
    如果(!choices.length){
        返回回调(preFIX);
    }
    为(变种C = 0; C<选择[0] .length; C ++){
        组合(choices.slice(1),回调(preFIX || [])CONCAT(选项[0] [C])。);
    }
}

VAR颜色=红,蓝,绿,黄];
VAR大小= [小,中等,大];
VAR体重= [重,轻];

组合([颜色,大小,重量],执行console.log);
 
JS创建Tag标签的方法详解

似乎工作...

  ['红','小','重']
['红','小','光明']
['红','中','重']
['红','中','光明']
['红','大','重']
['红','大','光明']
['蓝','小','重']
['蓝','小','光明']
['蓝','中','重']
['蓝','中','光明']
['蓝','大','重']
['蓝','大','光明']
[绿色,小,重]
['绿色','小','光明']
[绿色,中,重]
['绿色','中','光明']
['绿色','大','重']
['绿色','大','光明']
['黄','小','重']
['黄','小','光明']
['黄','中','重']
['黄','中','光明']
['黄','大','重']
['黄','大','光明']
 

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

解决方案

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

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

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

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' ]