using System;
using System.Linq;
namespace MyCompiler
{
class Program
{
public static void Main(string[] args)
{
PrintSeparator();
Evaluate(input: new int[] {3, 2, 1}, expectedOutput: new int[] {2, 3, 6});
PrintSeparator();
Evaluate(input: new int[] {1, 2, 3, 4, 5}, expectedOutput: new int[] {120, 60, 40, 30, 24});
PrintSeparator();
}
public static void Evaluate(int[] input, int[] expectedOutput)
{
var result = GetProductOfAllOtherElements(input);
Console.WriteLine("Input: [{0}]", string.Join(", ", input));
Console.WriteLine("ExpectedOutput: [{0}]", string.Join(", ", expectedOutput));
Console.WriteLine("Result: [{0}]", string.Join(", ", result));
Console.WriteLine("IsCorrect: [{0}]", Enumerable.SequenceEqual(result, expectedOutput));
}
public static void PrintSeparator(int size = 64)
{
Console.WriteLine(string.Empty.PadLeft(size, '-'));
}
public static int[] GetProductOfAllOtherElements(int[] numbers)
{
// Generate prefix products
var prefixProducts = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
if (i == 0)
{
prefixProducts[i] = numbers[i];
}
else
{
prefixProducts[i] = prefixProducts[i - 1] * numbers[i];
}
}
// Generate suffix products
var suffixProducts = new int[numbers.Length];
Array.Reverse(numbers);
for (var i = 0; i < numbers.Length; i++)
{
if (i == 0)
{
suffixProducts[i] = numbers[i];
}
else
{
suffixProducts[i] = suffixProducts[i - 1] * numbers[i];
}
}
Array.Reverse(suffixProducts);
Array.Reverse(numbers);
// Generate result from the product of prefixes and suffixes
var result = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
if (i == 0)
{
result[i] = suffixProducts[i + 1];
}
else if (i == numbers.Length - 1)
{
result[i] = prefixProducts[i - 1];
}
else
{
result[i] = prefixProducts[i - 1] * suffixProducts[i + 1];
}
}
return result;
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: