0

I have two arrays

x = [1 1 1 0 2 3 1 1]

y = [1 2 3 4 5 6 7 8]

How to calculate the sum of y's elements for all x(i) = 1 to get the result 1+2+3+7+8 ?

I have used for loop and if then method to calculate the sum value like this

if x(i) = 1 then sum = sum + y(i)

Have other methods to get the results (sum, average, count ...) ?

Thank you.

2 Answers 2

2

Since you only want to sum the numbers in y corresponding to 1s in x, but not 0s in x, you can multiply x * y which looks a bit cleaner than the If. Here are a few ways

Dim x = {1, 1, 1, 0, 0, 0, 1, 1}
Dim y = {1, 2, 3, 4, 5, 6, 7, 8}

' using a for loop
Dim sum1 As Integer = 0
For i = 0 To x.Length - 1
    sum1 += If(x(i) = 1, 1, 0) * y(i)
Next
Console.WriteLine(sum1)

' using LINQ #1
Dim sum2 As Integer = x.Select(Function(i, index) If(i = 1, 1, 0) * y(index)).Sum()
Console.WriteLine(sum2)

' using LINQ #2
Dim sum3 As Integer = x.Zip(y, Function(x1, y1) If(x1 = 1, 1, 0) * y1).Sum()
Console.WriteLine(sum3)

' using LINQ #3
Dim sum4 As Integer = Enumerable.Range(0, x.Length).Sum(Function(i) If(x(i) = 1, 1, 0) * y(i))
Console.WriteLine(sum4)

Console.ReadLine()
Sign up to request clarification or add additional context in comments.

2 Comments

But if the array x's elements are not only 0 or 1 but also have others like [0 0 1 2 0 3 0 1 0] ..... How to using LINQ to select and to sum the y(i) values for x(i)=1? Thank you.
Maybe something other than x = [1 1 1 0 0 0 1 1] would have made that more clear? But I'll edit my answer.
1

The For is very clear so I don't know why you wouldn't use it, but you can use LINQ for this as well:

Sub Main
    Dim x = {1, 1, 1, 0, 2, 3, 1, 1}
    Dim y = {1, 2, 3, 4, 5, 6, 7, 8}

    Dim sum = y.Where(Function(v, i) x(i) = 1).Sum()

    Console.WriteLine("Sum is {0}", sum)
End Sub

Prints

Sum is 21

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.