I have two arrays and need to add then together:
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
I need to go through every element and add them together (Arithmetically) so that I get:
1 2
2 3
3 4
In an array. How can I do this quickly? I'm using powershell 5.1.
CodePudding user response:
You can use a loop to either concatenate the numbers in each array to one another, or simply add them. In this case, we'll use a for
loop to iterate through each item in the array(s):
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
for ($i = 0; $i -lt $Array1.Count; $i )
{
Write-Host -Object "$($Array1[$i]) $($Array2[$i])"
}
<#
OutPut:
1 2
2 3
3 4
4 5
5 1
#>
Or, if you simply want to add them:
$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
for ($i = 0; $i -lt $Array1.Count; $i )
{
$Array1[$i] $Array2[$i]
}
<#
Output:
3
5
7
9
6
#>
CodePudding user response:
How can I do this quickly?
Assuming this is an important part of your question, offload the work to compiled C# code. The for
loop from Abraham Zinala's answer runs over a million item arrays in ~4 seconds for me. This same loop in C# runs in ~0.5 seconds:
Add-Type -Language CSharp @"
using System;
using System.Collections.Generic;
namespace AddHelper
{
public static class Adder
{
public static int[] AddArrays(int[] array1, int[] array2)
{
int[] result = new int[array1.Length];
for (int i = 0; i < array1.Length; i ) {
result[i] = array1[i] array2[i];
}
return result;
}
}
}
"@;
$result = [AddHelper.Adder]::AddArrays($Array1, $Array2)
Swapping everything in the PowerShell and C# from using arrays to using [System.Collections.Generic.List[int]]
brings that ~500ms down to ~430ms.