secondplace
secondplace

Reputation: 578

Powershell how to process a variable array

I have the following situation in powershell:

$arrayX = 0..1
$arrayY = 0..10

$array1 = @()
$array2 = @()
for ($i = 0; $i -lt $arrayY.Length; $i++){  
        $array1 += $arrayX[0] + $arrayY[$i]
        $array2 += $arrayX[1] + $arrayY[$i]
}

Both $arrayX and $arrayY can be variable in length. If i extend $arrayX by 1 i'll need to adjust the code to take the third value into account. like this:

$arrayX = 0..2
$arrayY = 0..10

$array1 = @()
$array2 = @()
$array3 = @()
for ($i = 0; $i -lt $arrayY.Length; $i++){  
        $array1 += $arrayX[0] + $arrayY[$i]
        $array2 += $arrayX[1] + $arrayY[$i]
        $array3 += $arrayX[2] + $arrayY[$i]
}

What is the best practice in a situation like this to have this work automatic?

Upvotes: 1

Views: 112

Answers (2)

n0rd
n0rd

Reputation: 12630

First, please consider not using the += operation with arrays: it will hurt performance a lot on larger arrays. Since you know the array size in advance you can allocate all required memory in advance:

$array1 = New-Object object[] $arrayY.Length

(you may want to use more specific type instead of object: int or float/double will work)

Next, instead of assigning each array to a variable, you can instead create array of arrays:

$arrayX = 0..2
$arrayY = 0..10

$resultArrays = New-Object int[][] $arrayX.Length

for ($x = 0; $x -lt $resultArrays.Length; ++$x)
{
    $resultArrays[$x] = New-Object int[] $arrayY.Length
}

for ($y = 0; $y -lt $arrayY.Length; ++$y)
{
    for ($x = 0; $x -lt $arrayX.Length; ++$x)
    {
        $resultArrays[$x][$y] = $arrayX[$x] + $arrayY[$y];
    }
}

for ($x = 0; $x -lt $resultArrays.Length; ++$x)
{
    Write-Output "array $($x): $($resultArrays[$x] -join ' ')"
}

Upvotes: 2

Nas
Nas

Reputation: 1263

Is this what you are looking for?

$arrayX = 0..2
$arrayY = 0..10

$arrayX | ForEach-Object {
    $aX = $_
    New-Variable -Name ('array' + $($aX+1)) -Value ($arrayY | ForEach-Object {$_ + $aX}) -Force
}

Upvotes: 0

Related Questions