How to calculate the dot product of two arrays in C#

4 Answers

0 votes
using System;

public class Program
{
	private static int calculate_dot_product(int[] arr1, int[] arr2) {
		int product = 0;
		int size = arr1.Length;

		for (int i = 0; i < size; i++) {
			product += arr1[i] * arr2[i];
		}

		return product;
	}
	public static void Main(string[] args)
	{
		int[] arr1 = new int[] {1, 4, 8, 9, 6};
		int[] arr2 = new int[] {0, 7, 1, 3, 40};

		Console.Write("Dot product = {0:D}", calculate_dot_product(arr1, arr2));
	}
}





/*
run:
  
Dot product = 303
  
*/

 



answered Feb 17, 2023 by avibootz
0 votes
using System;
using System.Linq;
  
public class Program
{
    private static int calculate_dot_product(int[] arr1, int[] arr2) {
        return arr1.Zip(arr2, (n1, n2) => n1 * n2).Sum();
    }
    public static void Main(string[] args)
    {
        int[] arr1 = new int[] {1, 4, 8, 9, 6};
        int[] arr2 = new int[] {0, 7, 1, 3, 40};
  
        Console.Write("Dot product = {0:D}", calculate_dot_product(arr1, arr2));
    }
}
  
  
  
  
  
/*
run:
    
Dot product = 303
    
*/

 



answered Feb 17, 2023 by avibootz
edited Feb 17, 2023 by avibootz
0 votes
using System;
using System.Linq;
 
public class Program
{
    private static int calculate_dot_product(int[] arr1, int[] arr2) {
        return Enumerable.Range(0, arr1.Length).Sum(i => arr1[i] * arr2[i]);
    }
    public static void Main(string[] args)
    {
        int[] arr1 = new int[] {1, 4, 8, 9, 6};
        int[] arr2 = new int[] {0, 7, 1, 3, 40};
 
        Console.Write("Dot product = {0:D}", calculate_dot_product(arr1, arr2));
    }
}
 
 
 
 
 
/*
run:
   
Dot product = 303

*/
   

 



answered Feb 17, 2023 by avibootz
edited Feb 17, 2023 by avibootz
0 votes
using System;
using System.Linq;
 
public class Program
{
    private static int calculate_dot_product(int[] arr1, int[] arr2) {
        return arr1.Select((n, i) => n * arr2[i]).Sum();
    }
    public static void Main(string[] args)
    {
        int[] arr1 = new int[] {1, 4, 8, 9, 6};
        int[] arr2 = new int[] {0, 7, 1, 3, 40};
 
        Console.Write("Dot product = {0:D}", calculate_dot_product(arr1, arr2));
    }
}
 
 
 
 
 
/*
run:
   
Dot product = 303
   
*/

 



answered Feb 17, 2023 by avibootz
...