Wednesday, March 4, 2015

C# solution for Codility Equi problem

If you have done the Equi Codility problem, you may have seen that a solution for this problem is posted here: http://blog.codility.com/2011/03/solutions-for-task-equi.html

Unfortunately, the solution is posted in C++ and not C#!!

Therefore, it takes some time to try and figure out the equivalent C# version for the Equi problem that will result in a 100% pass rate.

I have tried this particular solution on the Codility Equi demo problem and it has resulted in a 100% pass rate using C#:
class Solution

    {

        /// <summary>

        /// Returns the first equilibrium found of an array

        /// </summary>

        /// <param name="A">The array in question</param>

        /// <returns>The equilibrium of the array, if it exists, otherwise -1</returns>

        public int solution(int[] A)

        {

            // Default function result

            int equilibrium = -1;

 

            if (A != null && A.Length > 0)

            {

                // Strategy: Consider the input array two separate sub-arrays, one to the

                // left of the element being considered, the other to the right. We step 

                // through the array sequentially until the sums of the sub-arrays are equal.

 

                // Get initial left and right sums

                long sumLeft = 0;

                long sumRight = 0;

                for (int i = 0; i < A.Length; i++)

                {

                    sumRight += A[i];

                }

 

                // Traverse the array, looking for the first equilibrium

                for (int i = 0; i < A.Length; i++)

                {

                    var tempRight = sumRight - A[i];

                    if (sumLeft == tempRight)

                    {

                        // We have found a solution at the i-th element

                        equilibrium = i;

                        break;

                    }

                    else

                    {

                        // Prepare for next comparison

                        sumLeft += A[i];

                        sumRight = tempRight;

                    }

                }

            }

 

            // Return the result

            return equilibrium;

        }

    }



Hopefully this will provide a better understanding of what is evaluated for any people taking any Codility tests.




2 comments: