1

We've built a tool in C# that asks the user a series of multiple choice questions and then based on their answers it displays a list of products.

We're not doing any complicated logic, we just have products associated with specific answers and if that answer is chosen, then that product is added to the list of results.

We're ending up with scenarios where we're getting all products or no products, so we need to take a look at a more thorough way of coding our logic.

To start, I'm building a utility app in C# to help us validate the tool. The first task I want the utility to perform is to return all possible combinations of answers. I'm getting stuck on this. This is one of those math problems that makes my head hurt. Here's what the questions look like:

  • Question 1
    • Answer 1
    • Answer 2
  • Question 2
    • Answer 1
    • Answer 2
    • Answer 3
  • Question 3
    • Answer 1
    • Answer 2
    • Answer 3
  • Question 4
    • Answer 1
    • Answer 2

Can some one get me started in right direction on how to accomplish returning a list of all possible combinations of answers via C#? Thanks.

4

2 回答 2

9

您想要的操作称为笛卡尔积。例如,如果问题一和二的可能答案是{ a, b, c }{ d, e }那么笛卡尔积是{ {a, d}, {b, d}, {c, d}, {a, e }, {b, e}, {c, e} }

我写了一篇关于计算任意多个序列的笛卡尔积的文章;你可以在这里找到它:

http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx

还要看看这个 StackOverflow 问题:

生成所有可能的组合

于 2013-05-22T22:08:31.867 回答
1

这是一个简单的示例,有望说明一种(递归)技术:

void Main()
{
     int[] counts = new [] { 2, 2 };
     Choose(counts, 0, new Stack<string>());
}

void Choose(int[] AnswerCounts, int start, Stack<string> chosen) {
    for (int a=1; a<= AnswerCounts[start]; a++) {
        chosen.Push("Answer " + a.ToString());
        if (start < AnswerCounts.Length-1) {
            Choose(AnswerCounts, start+1, chosen);              
        }   
        else {                  
            Console.WriteLine(string.Join(", ", chosen.ToArray()));         
        }
        chosen.Pop();
    }   
}

输出:

Answer 1, Answer 1 
Answer 2, Answer 1 
Answer 1, Answer 2 
Answer 2, Answer 2 
于 2013-05-22T21:57:24.607 回答