David Avarage
David Avarage

Reputation: 57

How to add the numbers in two single-dimension arrays together and add that to a third list in powershell

Just to note, I literally want to add the numbers Arithmetically, not concatenate them, literally 1+1 (2); 2+2 (4); so adding the numbers in the lists. Sorry for the confusion.

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.

Upvotes: 1

Views: 100

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

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.

Upvotes: 1

Abraham Zinala
Abraham Zinala

Reputation: 4694

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
#>

Upvotes: 1

Related Questions