在Powershell中,我试图结合多个数组的元素来创建唯一字符串数组。我需要将每个数组中的每个元素与其他数组中的每个元素组合在一起。很难简明地解释我的意思,因此可能更容易展示。
我从看起来像这样的二维数组开始:
$array = @('this', ('A','B','C'), ('1','2','3','4'), 'that')
我需要创建一个数组,其内容将如下所示:
thisA1that
thisA2that
thisA3that
thisA4that
thisB1that
thisB2that
thisB3that
thisB4that
thisC1that
thisC2that
thisC3that
thisC4that
原始数组中数组的长度和数量是可变的,而且我不知道原始数组中项目的顺序。
到目前为止,我已经尝试了几种方法,但是我的逻辑是错误的。这是我第一次尝试解决方案:
$tempList = @()
#get total number of resources that will be created
$total = 1
for($i=0; $i -lt $array.Count; $i++){$total = $total * $array[$i].Count}
# build each resource from permutations of array parts
for ($i = 0; $i -lt $array.Count; $i++)
{
for ($j = 0; $j -lt $total; $j++)
{
$tempList += @('')
$idx = $total % $array[$i].Count
# item may either be string or an array. If string, just add it. If array, add the item at the index
if ($array[$i] -is [array]){ $tempList[$j] += $array[$i][$idx] }
else { $tempList[$j] += $array[$i] }
}
}
在此示例中,我使用模数运算符的逻辑是错误的,因此它每次都会获取每个数组的唯一第一个索引。经过进一步考虑,即使我确定了模数逻辑,整体逻辑仍然是错误的。例如,如果后两个数组的大小相同,则每次将“ A”与“ 1”配对,将“ B”与“ 2”配对,依此类推。
我敢肯定有办法做到这一点,但我似乎根本看不到它。
我认为答案是使用递归,这样您就可以处理以下事实:数组的数组可以是任意长度。此递归函数应:
我认为代码比上面的解释更好:
function Combine-Array {
[CmdletBinding()]
Param (
[string[][]]$Array
)
Process {
$current = $Array[0]
foreach ($item in $current) {
if ($Array.Count -gt 1) {
Combine-Array ([string[][]]@($Array | Select -Skip 1)) | %{'{0}{1}' -f $item, $_}
} else {
$item
}
}
}
}
Combine-Array @('this', ('A','B','C'), ('1','2','3','4'), 'that')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句