如何选择所有可能的组合?

时间:2012-09-11 16:12:44

标签: algorithm combinations

我们假设我们有以下贷款清单:

  • loan1
  • loan2
  • loan3
  • ...
  • loan10

我们的功能可以接受2到10笔贷款: function(loans)。 例如,以下是可能的:

  • function(loan1, loan2)
  • function(loan1, loan3)
  • function(loan1, loan4)
  • function(loan1, loan2, loan3)
  • function(loan1, loan2, loan4)
  • function(loan1, loan2, loan3, loan4, loan5, loan6, loan7, loan8, loan9, loan10)

如何编写代码以将所有可能的组合传递给该函数?

3 个答案:

答案 0 :(得分:2)

RosettaCode上,您已经实现了多种语言的生成组合,请选择自己。

答案 1 :(得分:0)

以下是我们如何在ruby中做到这一点:

loans= ['loan1','loan2', ... , 'loan10']

def my_function(loans)
  array_of_loan_combinations = (0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}

  array_of_loan_combinations.each do |combination|
    //do something
  end
end

致电:

my_function(loans);

答案 2 :(得分:0)

我编写了一个类来处理使用二项式系数的常用函数,这是您的问题所处的问题类型。它执行以下任务:

以任意N选择K到文件的格式输出所有K索引。 K索引可以用更具描述性的字符串或字母代替。这种方法使解决这类问题变得非常简单。

将K索引转换为已排序二项系数表中条目的正确索引。这种技术比依赖迭代的旧发布技术快得多。它通过使用Pascal三角形中固有的数学属性来实现。我的论文谈到了这一点。我相信我是第一个发现和发布这种技术的人,但我可能错了。

将已排序的二项系数表中的索引转换为相应的K索引。我相信它可能比你找到的链接更快。

使用Mark Dominus方法计算二项式系数,这种方法很可能会溢出并使用更大的数字。

该类是用.NET C#编写的,它提供了一种通过使用通用列表来管理与问题相关的对象(如果有)的方法。此类的构造函数采用名为InitTable的bool值,当为true时,将创建一个通用列表来保存要管理的对象。如果此值为false,则不会创建表。不需要创建表来执行上述4种方法。提供了访问器方法来访问该表。

有一个关联的测试类,它显示了如何使用该类及其方法。它已经过2个案例的广泛测试,并且没有已知的错误。

要阅读有关此课程并下载代码,请参阅Tablizing The Binomial Coeffieicent。

将此课程转换为您选择的语言应该不难。

要解决您的问题,您可能需要编写一个新的贷款函数,该函数将一组贷款对象作为输入,并使用BinCoeff类处理这些对象。在C#中,要获取每个唯一组合的贷款数组,可以使用类似下面的示例代码:

void LoanCombinations(Loan[] Loans)
{
   // The Loans array contains all of the loan objects that need
   // to be handled.
   int LoansCount = Loans.Length;
   // Loop though all possible combinations of loan objects.
   // Start with 2 loan objects, then 3, 4, and so forth.
   for (int N = 2; N <= N; N++)
   {
      // Loop thru all the possible groups of combinations.
      for (int K = N - 1; K < N; K++)
      {
         // Create the bin coeff object required to get all
         // the combos for this N choose K combination.
         BinCoeff<int> BC = new BinCoeff<int>(N, K, false);
         int NumCombos = BinCoeff<int>.GetBinCoeff(N, K);
         int[] KIndexes = new int[K];
         // Loop thru all the combinations for this N choose K.
         for (int Combo = 0; Combo < NumCombos; Combo++)
         {
            // Get the k-indexes for this combination, which in this case
            // are the indexes to each loan in Loans.
            BC.GetKIndexes(Loop, KIndexes);
            // Create a new array of Loan objects that correspond to
            // this combination group.
            Loan[] ComboLoans = new Loan[K];
            for (int Loop = 0; Loop < K; Loop++)
               ComboLoans[Loop] = Loans[KIndexes[Loop]];
            // Call the ProcessLoans function with the loans to be processed.
            ProcessLoans(ComboLoans);
         }
      }
   }
}

我没有测试过上面的代码,但总的来说它应该可以解决你的问题。