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

时间:2022-05-05 21:37:30

Consider the following multiple choice question:

考虑以下多项选择题:

What's the color of apples?

苹果的颜色是什么?

  • a. red
  • b. green
  • c. blue
  • 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?

......但后来我不知道下一步应该是什么。有任何想法吗?

2 个解决方案

#1


0  

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

#2


0  

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();
}

#1


0  

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

#2


0  

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();
}