Home > front end >  Multiplying the output of arrays
Multiplying the output of arrays

Time:09-21

I'm trying to create a console program that multiplies the output of array 1 {1, 2, 3, 4, 5} and array 2 {12, 14, 15, 16, 17} to array 3 {8, 4, 7, 2, 1} in reverse.

For example: array 1 = {1, 2, 3, 4, 5} * array2 = {17, 16, 15, 14, 12} expected output is {17, 32, 45, 56, 60}.

To get the output for array number 3 I need to reverse the values of array3 and multiple it by the output of arrays 1 and 2. For example: array3 = {60, 56, 45, 32, 17} * product of array 1 & 2 {17, 32, 45, 56, 60}.

My problem is I don't have any idea how to multiply the output of arrays 1 and 2 to array 3. So far here is my code:

            int[] array1 = {1, 2, 3, 4, 5};
            Console.Write("\nArray 1: ");
            Console.WriteLine(String.Join(", ", array1));

            int[] array2 = {12, 14, 15, 16, 17};
            Console.Write("Array 2: ");
            Console.WriteLine(String.Join(", ", array2));


            int[] array3 = {8, 4, 7, 2, 1};
            Console.Write("Array 3: ");
            Console.WriteLine(String.Join(", ", array3));

            Console.Write("\nProduct of array 1 and 2: ");
            Console.WriteLine(string.Join(", ", array2.Reverse().Zip(array1, (x, y) => x * y)));


            Console.Read();

In a previous iteration of this question asked under another account I was given suggestion to use

array3 = array2.Reverse().Zip(array1, (a, b) => a*b).ToArray();

but I think I want something else as I need "to multiply the output of arrays 1 and 2 to array 3".

CodePudding user response:

Something like this. A bit hardcoded but you get the idea

var a1 = new int[] {1,2,3,4,5};
var a2 = new int[] {6,7,8,9,10};
var a3 = new int[] {10,20,30,40,50};
var out1and2 = new int[5];
var out3 = new int[5];

for (int i = 0; i < 5; i  )
{
    out1and2[i]  = a1[i] * a2[i];
    out3[i] = out1and2[i] * a3[a3.Length - 1 - i]; // reverse by taking max and subtracting

}
        
for (int i = 0; i < 5; i  )
    Console.WriteLine(out1and2[i]);
    
Console.WriteLine("----------------------");

for (int i = 0; i < 5; i  )
    Console.WriteLine(out3[i]);

6
14
24
36
50
----------------------
300
560
720
720
500

CodePudding user response:

Something like this :

var arr = array2.Reverse().Zip(array1, (x, y) => x * y).ToArray();
Console.WriteLine(string.Join(", ", array3.Reverse().Zip(arr, (x, y) => x * y)));

output will be : 17, 64, 315, 224, 480

  • Related