Excel VBA的组合算法

时间:2016-02-11 17:47:02

标签: excel algorithm vba combinations

让我们说我有一组项目如下:

Item    Units
Apples    5
Pears     5
Carrots   1
Oranges   4

我有六个人可以给他们这些物品。我们打电话给他们:

Mr. A
Mr. B
Mr. C
Mr. D
Mr. E
Mr. F

我需要一个Excel VBA代码,它可以检索上面向不同人员分享上述项目的所有潜在组合。请注意,(i)订单并不重要;(ii)一个人可能拥有同一商品的多个单元。

为了报告这些信息,我想到的结构类似于下面的结构:

                          Mr A                                 Mr B                   ...
             Apples  Pears  Carrots  Oranges       Apples  Pears  Carrots  Oranges    ...
Scenario 1     1       0       1        2             2      2       0        0       ...
Scenario 2     1       0       1        1             2      2       0        0       ...
...

我知道组合的数量会很大,但不要考虑计算要求。

我一直试图找出算法,但一直无法实现。

提前致谢,

1 个答案:

答案 0 :(得分:0)

我试图用A先生和B先生进行测试,有360种不同的情景。

Sub distr_list()
Dim apple_a, apple_b

Count = 1

Cells(Count, 4) = "apple_a"
Cells(Count, 5) = "pear_a"
Cells(Count, 6) = "carrot_a"
Cells(Count, 7) = "orange_a"

Cells(Count, 9) = "apple_b"
Cells(Count, 10) = "pear_b"
Cells(Count, 11) = "carrot_b"
Cells(Count, 12) = "orange_b"

For apple_a = 0 To 5
For apple_b = 0 To 5

For pear_a = 0 To 5
For pear_b = 0 To 5

For carrot_a = 0 To 1
For carrot_b = 0 To 1

For orange_a = 0 To 4
For orange_b = 0 To 4


 If apple_a + apple_b = 5 Then
    If pear_a + pear_b = 5 Then
        If carrot_a + carrot_b = 1 Then
            If orange_a + orange_b = 4 Then

    Cells(Count + 1, 4) = apple_a
    Cells(Count + 1, 5) = pear_a
    Cells(Count + 1, 6) = carrot_a
    Cells(Count + 1, 7) = orange_a

    Cells(Count + 1, 9) = apple_b
    Cells(Count + 1, 10) = pear_b
    Cells(Count + 1, 11) = carrot_b
    Cells(Count + 1, 12) = orange_b

    Count = Count + 1

 End If
 End If
 End If
 End If

Next
Next
Next
Next
Next
Next
Next
Next

End Sub

您可以为其余部分应用相同的逻辑。