Example #1
0
        /// <summary>
        /// Performs a smaller-to-bigger summation of sequence members.
        /// Works slightly slower than a simple sequential summation,
        /// but as smallest values are summed up first, this method
        /// significantly increases precision if the sequence doesn't non-decrease
        /// monotonously and consequent values are of different degrees.
        ///
        /// Requires a general term formula dependent on both argument and integer index (<paramref name="memberFormula"/>) as well as the current function argument.
        /// Also requires a comparer allowing of knowing which sequence element is bigger and which is smaller.
        /// </summary>
        /// <param name="startIndex">The inclusive beginning index of sequence summation.</param>
        /// <param name="endIndex">The inclusive ending index of sequence summation.</param>
        /// <param name="comparer">The comparer to compare values of type <typeparamref name="T"/>. Should return a positive value if the first value is bigger than the second, zero value if they are equal, and a negative value if the first object is less.</param>
        /// <param name="memberFormula">The general term formula dependent on both argument and integer index.</param>
        /// <param name="argument">The current argument for the sequence.</param>
        /// <returns>The result of sequential summation of the sequence starting with index <paramref name="startIndex"/> and ending with index <paramref name="endIndex"/>, both inclusive.</returns>
        public T Sum_SmallerToBigger(T argument, Func <T, int, T> memberFormula, int startIndex, int endIndex, IComparer <T> comparer)
        {
            IPriorityQueue <T> sequence = new BinaryHeap <T>(comparer.GetReverseComparer());

            if (startIndex >= endIndex)
            {
                for (int i = startIndex; i <= endIndex; i++)
                {
                    sequence.Insert(memberFormula(argument, i));
                }
            }
            else
            {
                for (int i = endIndex; i >= startIndex; i--)
                {
                    sequence.Insert(memberFormula(argument, i));
                }
            }

            T sum = this.Zero;

            while (!sequence.IsEmpty)
            {
                sum = this.OperatorPlus(sum, sequence.Pop());
            }

            return(sum);
        }