Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA-将所有数字排列写入数组_Excel_Vba_Permutation - Fatal编程技术网

Excel VBA-将所有数字排列写入数组

Excel VBA-将所有数字排列写入数组,excel,vba,permutation,Excel,Vba,Permutation,目前,我正在手动将值输入数组,对数组(a、b、c)进行签名。其中c是级别编号。请看下面的输出,其中c=1,数组只有两个输入。当c=2(或2级)时,有4个输入。3级=8个输入,4级有16个输入。但是把这些都写出来会让人感到非常厌烦 我真的很挣扎。我需要将1或2的所有组合写入数组,并查找以下输出: 1 2 1, 1 1, 2 2, 1 2, 2 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2, 1 2, 1,

目前,我正在手动将值输入数组,对数组(a、b、c)进行签名。其中c是级别编号。请看下面的输出,其中c=1,数组只有两个输入。当c=2(或2级)时,有4个输入。3级=8个输入,4级有16个输入。但是把这些都写出来会让人感到非常厌烦

我真的很挣扎。我需要将1或2的所有组合写入数组,并查找以下输出:

1    
2
1, 1    
1, 2    
2, 1
2, 2  
1, 1, 1  
2, 1, 1    
1, 2, 1    
1, 1, 2    
2, 2, 1    
2, 1, 2    
1, 2, 2    
2, 2, 2    
1, 1, 1, 1    
2, 1, 1, 1
etc
请看下面我走了多远,但不知道该怎么做,以区分1或2。任何帮助都将不胜感激。目前,我自己手动输入组合,但我知道,我拥有的维度越多,它就越大

我不介意为每个级别创建一个for循环

levels_to_use = 4
for i = 1 to levels_to_use  ^ 2
    for j = 1 to levels_to_use 
        ' in here how to chose between 1 or 2
        sign_array(i, j, levels_to_use) = 1
    next
next

不久前,我没有更好的事情要做,我写的代码正是您想要的-

因此,如果您稍微更改它,避免使用
\ucode>并将
size
变量放入循环中,它将打印所需的结果:

如果将
c=Array(1,2)
更改为
c=Array(1,2,3)
,则会向系统添加第三个元素

Sub Main()

    Static size         As Long
    Static c            As Variant
    Static arr          As Variant
    Static n            As Long

    c = Array(1, 2)
    n = UBound(c) + 1
    For size = 1 To 4
        ReDim arr(size - 1)
        EmbeddedLoops 0, size, c, n, arr
        Debug.Print "---------"
    Next size

End Sub

Function EmbeddedLoops(index, k, c, n, arr)

    Dim i                   As Variant
    If index >= k Then
        PrintArrayInOneLine arr
    Else
        For Each i In c
            arr(index) = i
            EmbeddedLoops index + 1, k, c, n, arr
        Next i
    End If

End Function

Public Sub PrintArrayInOneLine(myArray As Variant)

    Dim counter     As Long
    Dim sArray      As String
    For counter = LBound(myArray) To UBound(myArray)
        sArray = sArray & myArray(counter)
    Next counter
    Debug.Print sArray

End Sub

您需要覆盖多少“级别”?或者你需要它是动态的吗?理想情况下是动态的:-(我似乎无法编辑主要帖子,我的输出数字是错误的。级别2=1,1-1,2-2,1-2,2例如,你可以循环2^x,其中x是级别,然后使用十进制到二进制转换器,并将0替换为2?输出,例如0000=00001=10010=2…仅供参考,你想要的是所谓的排列。如果你在上面搜索,你可以找到一些解决方案l。)ike.你真是天才!这样我就可以使用sArray并在字符串中的每个字符上循环?@Surreall-欢迎。关于
sArray
并在其字符上循环-最好避免写入字符串,而只是在
myArray
中循环。这很有效,谢谢!这让我发疯了。