DEV Community

Discussion on: Daily Coding Problem #2

Collapse
 
mdusoemsa profile image
mdusoemsa

Part 2 solution, slightly better than O(n2), using a copy to initialize the array, and the inner loop runs 2 fewer times than the outer.

namespace Playground
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = new int[] {1, 2, 3, 4, 5};

            var output = ComputeProducts(input);

            foreach (int i in output)
            {
                Console.Write($"{i}\t");
            }

            Console.ReadLine();
        }

        static int[] ComputeProducts(int[] source)
        {
            var count = source.Length;
            // making a few assumptions for edge cases...
            if (count < 2)
                return source;

            if (count == 2)
                return new[] {source[1], source[0]};

            var result = new int[count];
            // initialize the array, eliminating the need to do a "set to 1" step
            Array.Copy(source,1,result,0,count - 1);
            result[count - 1] = source[0];

            // loop the result
            for (int i = 0; i < count; i++)
            {
                // we skip the current index, and the next one has already been set above
                for (int j = 2; j < count; j++)
                {
                    result[i] *= source[(j + i) % count];
                }
            }

            return result;
        }
    }
}