Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
1
Indexable
Never
using System;

namespace FindBalanceElementTask
{
    /// <summary>
    /// Class for operations with arrays.
    /// </summary>
    public static class ArrayExtension
    {
        /// <summary>
        /// Finds an index of element in an integer array for which the sum of the elements
        /// on the left and the sum of the elements on the right are equal.
        /// </summary>
        /// <param name="array">Source array.</param>
        /// <returns>The index of the balance element, if it exists, and null otherwise.</returns>
        /// <exception cref="ArgumentNullException">Thrown when source array is null.</exception>
        /// <exception cref="ArgumentException">Thrown when source array is empty.</exception>
        public static int? FindBalanceElement(int[]? array)
        {
            var sum = 0;
            foreach (var item in array)
            {
                sum += item;
            }

            int i = 0,
               left = 0,
               right = sum - array[0];

            while (left < right)
            {
                left += array[i++];
                right -= array[i];
            }

            if (array.Length == 0)
            {
                throw new ArgumentNullException();
            }

            if (left == right)
            {
                return i;
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}