How to replace each element in array with the product of every other elements in C#

1 Answer

0 votes
using System;

public class Program
{
	public static void product_of_every_other_elements(int[] arr) {
		int size = arr.Length;

		if (size == 0) {
			return;
		}

		int[] left = new int[size];
		int[] right = new int[size];

		left[0] = 1;
		for (int i = 1; i < size; i++) {
			left[i] = arr[i - 1] * left[i - 1];
		}

		right[size - 1] = 1;
		for (int j = size - 2; j >= 0; j--)	{
			right[j] = arr[j + 1] * right[j + 1];
		}

		for (int i = 0; i < size; i++) {
			arr[i] = left[i] * right[i];
		}
	}
	public static void Main(string[] args)
	{
		int[] array = new int[]{1, 2, 3, 4, 5};

		product_of_every_other_elements(array);

		for (int i = 0; i < array.Length; i++) {
			Console.Write(array[i] + " ");
		}
	}
}




/*
run:
  
120 60 40 30 24 
  
*/

 



answered Sep 22, 2023 by avibootz
...