首页 UiBot教程 当前文章

获取一个数组的所有排列组合方式

xLeaves(xxrpa) 发布于 2022年08月18日 17:46:37


主要应用场景:对账。

需要对未办结的数据进行尽可能的金额匹配,解决思路是计算出所有的匹配可能,然后计算出这些可能性的所有金额。

再从这些金额中匹配相等项,则对账成功。


下面是获取数组所有排列组合方式的实现代码,输入一个数组,返回包含这个数组组合方式的新数组:

// 左移位
Function shl(num, c)
    Dim a = 2
    For i = 2 to c
        a = a * 2
    next
    return a * num
end Function

// 右移位
Function shr(num, c)
    for i = 1 to c
        num = Math.Int(num / 2)
    next
    return num
end Function

// 求一个数组元素的所有排列组合
Function 求数组组合(arr)
    Dim arrRet = []
    Dim arrRet_Count = 0
    Dim iSize = len(arr)
    Dim iCount = shl(1, iSize) - 1
    for i = 1 to iCount
        Dim arrItem = []
        Dim arrItem_Count = 0
        Dim iCurPos = iSize - 1
        Dim iNumber = i
        Do While (iNumber <> 0)
            if (iNumber Mod 2) = 1
                if arr[iCurPos] <> null
                    arrItem[arrItem_Count] = arr[iCurPos]
                    arrItem_Count = arrItem_Count + 1
                end if
            end if
            iNumber = shr(iNumber, 1)
            iCurPos = iCurPos - 1
        Loop
        arrRet[arrRet_Count] = arrItem
        arrRet_Count = arrRet_Count + 1
    next
    return arrRet
End Function

TracePrint 求数组组合([1, 2, 3, 4, 5, 6])

运行后,得到结果如下:

[
	[ 6 ],
	[ 5 ],
	[ 6, 5 ],
	[ 4 ],
	[ 6, 4 ],
	[ 5, 4 ],
	[ 6, 5, 4 ],
	[ 3 ],
	[ 6, 3 ],
	[ 5, 3 ],
	[ 6, 5, 3 ],
	[ 4, 3 ],
	[ 6, 4, 3 ],
	[ 5, 4, 3 ],
	[ 6, 5, 4, 3 ],
	[ 2 ],
	[ 6, 2 ],
	[ 5, 2 ],
	[ 6, 5, 2 ],
	[ 4, 2 ],
	[ 6, 4, 2 ],
	[ 5, 4, 2 ],
	[ 6, 5, 4, 2 ],
	[ 3, 2 ],
	[ 6, 3, 2 ],
	[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