简体   繁体   English

如何计算所有可能的多项选择组合?

[英]How to calculate all possible multiple choice combinations?

Consider the following multiple choice question: 考虑以下选择题:

What's the color of apples? 苹果是什么颜色的?

  • a. 一种。 red 红色
  • b. b。 green 绿色
  • c. C。 blue 蓝色
  • d. d。 black 黑色

Now, I want to calculate all it's possible answers and I could do it manually, like so...: 现在,我想计算所有可能的答案,并且可以手动完成,如下所示:

a
b
c
d
a, b
a, c
a, d
b, c
b, d
c, d
a, b, c
a, b, d
a, c, d
b, c, d
a, b, c, d

... but that's prone to human error. ...但这很容易发生人为错误。 How could I do this programmatically with JavaScript? 如何使用JavaScript以编程方式执行此操作?

My initial thought is to define the total number of choices (a,b,c,d = 4)...: 我最初的想法是定义选择的总数(a,b,c,d = 4)...:

const TOTAL_CHOICES = 4;

// TO-DO

... but then I don't know what the next step should be. ...但是后来我不知道下一步应该怎么做。 Any ideas? 有任何想法吗?

With the help of @nenad-vracar's comment I found a solution: 借助@ nenad-vracar的评论,我找到了一个解决方案:

function combinations(str) {
  var fn = function(active, rest, a) {
    if (!active && !rest)
      return;
    if (!rest) {
      a.push(active);
    } else {
      fn(active + rest[0], rest.slice(1), a);
      fn(active, rest.slice(1), a);
    }
    return a;
  }
  return fn("", str, []);
}

var result = combinations('abcd').sort();

for (combination of result) {
    document.body.innerHTML += combination + '<br>';
}

This will output: 这将输出:

a
ab
abc
abcd
abd
ac
acd
ad
b
bc
bcd
bd
c
cd
d

This implements the way I suggested in my comment. 这实现了我在评论中建议的方式。

var choices = ['d','c','b','a'];
var numCombos=Math.pow(2,choices.length);
var binNum;
writeln('Combos are:');
for (i=0;i<numCombos;i++)
{
 binNum=(i.toString(2));
 while (binNum.length<choices.length)
  binNum='0'+binNum;
 for (j=choices.length-1;j>=0;j--){
   if (binNum[j]=='1') write(choices[j]);}
 writeln();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM