Exemple #1
0
 /// <summary>
 /// Validates that the specified value is between a specified exclusive minimum and maximum
 /// value.
 /// </summary>
 /// <typeparam name="T">The type of the value being validated.</typeparam>
 /// <param name="value">The value to validate is between the specified minimum and maximum
 /// value.</param>
 /// <param name="minValue">The minimum value to validate against.</param>
 /// <param name="maxValue">The maximum value to validate against.</param>
 /// <param name="valueName">The name of the parameter being validated.</param>
 /// <param name="comparer">The comparer to use to compare the specified values.</param>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than or
 /// equal to <paramref name="minValue"/>, or <paramref name="value"/> is greater than or
 /// equal to <paramref name="maxValue"/>.</exception>
 public static void IsBetween <T>(
     T value,
     T minValue,
     T maxValue,
     string valueName,
     IComparer <T> comparer)
 {
     if (comparer?.Compare(value, minValue) <= 0 || comparer?.Compare(value, maxValue) >= 0)
     {
         throw new ArgumentOutOfRangeException(
                   valueName,
                   Invariant($"Value must be between {minValue} and {maxValue}."));
     }
 }
 protected virtual int FindIndex(object item, object seed, IComparer comparer, int low, int high)
 {
     if (comparer != null)
     {
         ListComparer comparer2 = comparer as ListComparer;
         if (comparer2 != null)
         {
             comparer2.Reset();
         }
         CollectionViewGroupComparer comparer3 = comparer as CollectionViewGroupComparer;
         if (comparer3 != null)
         {
             comparer3.Reset();
         }
         int num = low;
         while (num < high)
         {
             CollectionViewGroupInternal internal2 = base.ProtectedItems[num] as CollectionViewGroupInternal;
             object y = (internal2 != null) ? internal2.SeedItem : base.ProtectedItems[num];
             if ((y != DependencyProperty.UnsetValue) && (comparer.Compare(seed, y) < 0))
             {
                 return num;
             }
             num++;
         }
         return num;
     }
     return high;
 }
            public int Compare(BenchmarkCase x, BenchmarkCase y)
            {
                if (x == null && y == null)
                {
                    return(0);
                }
                if (x != null && y == null)
                {
                    return(1);
                }
                if (x == null)
                {
                    return(-1);
                }

                foreach (var rule in order)
                {
                    int compare = rule switch
                    {
                        BenchmarkLogicalGroupRule.ByMethod => targetComparer?.Compare(x.Descriptor, y.Descriptor) ?? 0,
                        BenchmarkLogicalGroupRule.ByJob => jobComparer?.Compare(x.Job, y.Job) ?? 0,
                        BenchmarkLogicalGroupRule.ByParams => paramsComparer?.Compare(x.Parameters, y.Parameters) ?? 0,
                        BenchmarkLogicalGroupRule.ByCategory => categoryComparer?.Compare(x.Descriptor.Categories, y.Descriptor.Categories) ?? 0,
                        _ => throw new ArgumentOutOfRangeException()
                    };
                    if (compare != 0)
                    {
                        return(compare);
                    }
                }
                return(string.CompareOrdinal(x.DisplayInfo, y.DisplayInfo));
            }
        }
Exemple #4
0
        /// <summary>
        /// Computes difference of two sorted sequences.
        /// </summary>
        /// <remarks>
        /// <para>Both set1 and set2 must be sorted in ascending order with respect to comparer.</para>
        /// <para>Difference contains elements present in set1, but not in set2.</para>
        /// <para>Result is written to the output iterator one member at a time</para>
        /// 
        /// <para>For multisets, if set1 contains k equal elements, and set2 contains
        /// m elements equal to those k, then max(k-m,0) elements from set1 are
        /// included in the output.</para>
        /// <para>Complexity: linear on combined number of items in both sequences</para>
        /// </remarks>
        /// <example>
        /// <para>set1 = {"a", "b", "test", "tEst", "z" }</para>
        /// <para>set2 = {"a", "TEST", "z", "Z" }</para>
        /// <para>comparer = case insensitive comparer</para>
        /// <para>output = {"b", "tEst"}</para>
        /// </example>
        public static void Difference(IEnumerable set1, IEnumerable set2, IComparer comparer, IOutputIterator output)
        {
            var enum1 = set1.GetEnumerator();
            var enum2 = set2.GetEnumerator();

            var have1 = enum1.MoveNext();
            var have2 = enum2.MoveNext();

            while (have1 && have2)
            {
                var compare = comparer.Compare(enum1.Current, enum2.Current);
                if (compare < 0)
                {
                    output.Add(enum1.Current);
                    have1 = enum1.MoveNext();
                }
                else if (compare > 0)
                {
                    have2 = enum2.MoveNext();
                }
                else
                {
                    have1 = enum1.MoveNext();
                    have2 = enum2.MoveNext();
                }
            }

            while (have1)
            {
                output.Add(enum1.Current);
                have1 = enum1.MoveNext();
            }
        }
Exemple #5
0
		/// <summary>
		/// Don't overwrite already cached items
		/// </summary>
		/// <param name="txTimestamp"></param>
		/// <param name="newVersion"></param>
		/// <param name="comparator"></param>
		/// <returns></returns>
		public bool IsPuttable(long txTimestamp, object newVersion, IComparer comparator)
		{
			// we really could refresh the item if it  
			// is not a lock, but it might be slower
			//return freshTimestamp < txTimestamp
			return version != null && comparator.Compare(version, newVersion) < 0;
		}
Exemple #6
0
 private static int Compare(IComparer<Object> comparer, Object[] array, int leftIndex, int rightIndex) {
     // item 64
     Object left = array[leftIndex];
     Object right = array[rightIndex];
     // item 56
     return comparer.Compare(left, right);
 }
Exemple #7
0
		private SetOp() { } // disable construction

		/// <summary>
		/// Computes union of two sorted sequences.
		/// </summary>
		/// <remarks>
		/// <para>Both set1 and set2 must be sorted in ascending order with respect to comparer.</para>
		/// <para>Union contains elements present in one or both ranges.</para>
		/// <para>Result is written to the output iterator one member at a time</para>
		/// 
		/// <para>Union differs from <see cref="Merge">Merge</see> for multisets.</para>
		/// 
		/// <para>If k equal elements are present in set1 and m elements equal to those k
		/// are present in set2,then k elements from set1 are included in the output, 
		/// followed by max(m-k, 0) elements from set2. The total of max(k,m) are
		/// added to the output. If you'd like to have m+k elements, use Merge function.
		/// </para>
		/// <para>Complexity: linear on combined number of items in both sequences</para>
		/// </remarks>
		/// <example>
		/// <para>set1 = { "a", "test", "Test", "z" }</para>
		/// <para>set2 = { "b", "tEst", "teSt", "TEST", "Z" }</para>
		/// <para>comparer is a case-insensitive comparer</para>
		/// <para>The following elements will be added to output:
		/// {"a", "b", "test", "Test", "TEST", "z" }</para>
		/// </example>
		public static void Union(IEnumerable set1, IEnumerable set2, IComparer comparer, IOutputIterator output) {
			IEnumerator enum1 = set1.GetEnumerator();
			IEnumerator enum2 = set2.GetEnumerator();

			bool have1 = enum1.MoveNext();
			bool have2 = enum2.MoveNext();

			while (have1 && have2) {
				int compare = comparer.Compare(enum1.Current, enum2.Current);

				if (compare < 0) {
					output.Add(enum1.Current);
					have1 = enum1.MoveNext();
				} else if (compare > 0) {
					output.Add(enum2.Current);
					have2 = enum2.MoveNext();
				} else {
					output.Add(enum1.Current);
					have1 = enum1.MoveNext();
					have2 = enum2.MoveNext();
				}
			}

			while (have1) {
				output.Add(enum1.Current);
				have1 = enum1.MoveNext();
			}

			while (have2) {
				output.Add(enum2.Current);
				have2 = enum2.MoveNext();
			}
		}
Exemple #8
0
 public int Compare(Benchmark x, Benchmark y) => new[]
 {
     paramsComparer?.Compare(x.Parameters, y.Parameters) ?? 0,
     jobComparer?.Compare(x.Job, y.Job) ?? 0,
     targetComparer?.Compare(x.Target, y.Target) ?? 0,
     string.CompareOrdinal(x.DisplayInfo, y.DisplayInfo)
 }.FirstOrDefault(c => c != 0);
Exemple #9
0
            private int Compare(object x, object y)
            {
                int result = 0;

                if (_propertyType == null)
                {
                    if (x != null)
                    {
                        _propertyType = GetPropertyType(x);
                    }
                    if (_propertyType == null && y != null)
                    {
                        _propertyType = GetPropertyType(y);
                    }
                }

                object v1 = GetValue(x);
                object v2 = GetValue(y);

                if (_propertyType != null && _internalComparer == null)
                {
                    _internalComparer = GetComparerForType(_propertyType);
                }

                result = _internalComparer?.Compare(v1, v2) ?? 0;

                if (_descending)
                {
                    return(-result);
                }
                else
                {
                    return(result);
                }
            }
        public static int Partition( this int[] arr, int start, int end, int pivot,
            IComparer<int> comparer)
        {
            if ( pivot < start || pivot > end )
                throw new IndexOutOfRangeException( "Pivot was out of range" );

            if ( end <= start )
                return pivot;

            int pVal = arr[pivot];
            arr.Swap( end, pivot );

            int i = start, j = end - 1;
            while ( i < j )
            {
                while ( i < j && comparer.Compare( arr[i], pVal ) <= 0 )
                    ++i;

                while ( i < j && comparer.Compare( arr[j], pVal ) > 0 )
                    --j;

                if ( i < j )
                    arr.Swap( i, j );
            }

            if ( comparer.Compare( arr[i], pVal ) <= 0 )
                ++i;

            arr[end] = arr[i];
            arr[i] = pVal;
            return i;
        }
Exemple #11
0
    /// <summary>
    /// A simple bubble sort for two arrays, limited to some region of the arrays.
    /// This is a regular bubble sort, nothing fancy.
    /// </summary>
    public static void SimpleSort(Array array, Array items, int startingIndex, int length, IComparer comparer)
    {
        bool finished = false;
        while (!finished)
        {
            bool swapped = false;
            for (int g = startingIndex; g < startingIndex + length - 1; g++)
            {
                Object first = array.GetValue(g);
                Object second = array.GetValue(g + 1);
                int comparison = comparer.Compare(first, second);
                if (comparison == 1)
                {
                    Swap(g, g + 1, array, items);
                    swapped = true;

                    first = array.GetValue(g);
                    second = array.GetValue(g + 1);
                }
            }
            if (!swapped)
            {
                finished = true;
            }
        }
    }
 private static void BubbleSort(int[][] array, IComparer comparer)
 {
     int length = array.Length;
     for (int i = 0; i < length; i++)
         for (int j = 0; j < length - i - 1; j++)
             if (comparer.Compare(array[j], array[j+1]) > 0)
                 Swap(ref array[j], ref array[j + 1]);
 }
 public static void SortWithInterfaces(double[][] array, IComparer<double[]> comparer)
 {
     for (int i = 0; i < array.Length - 1; ++i)
         for (int j = 0; j < array.Length - i - 1; ++j)
         {
             if (comparer.Compare(array[j], array[j + 1]) > 0)
                 Swap(ref array[j], ref array[j + 1]);
         }
 }
Exemple #14
0
		static bool Contains(IList list, object value, IComparer comparer)
		{
			foreach(object item in list) {
				if(0 == comparer.Compare(item, value)) {
					return true;
				}
			}
			return false;
		}
Exemple #15
0
 private void SortColumn(int idx, IComparer<Object> cmp)
 {
     for(int i = 1; i < table.Count; i++) {
         for(int j = i; j > 0; j--)
         {
             if (cmp.Compare(table[j][idx], table[j - 1][idx]) > 0)
                 SwapTable(j, j - 1);
         }
     }
 }
 private static void BubbleSort(int[][] array, IComparer<int[]> comparer)
 {
     int n = array.Length;
     while (n- 1 > 0)
     {
         for (int i = 0; i < array.Count() - 1; i++)
             if (comparer.Compare(array[i], array[i + 1]) > 0)
                 Swap(ref array[i], ref array[i+1]);
         n--;
     }
 }
 ///<param name="list">List to sort</param>
 ///<param name="lbound">Lower bound, smallest index to include in sort</param>
 ///<param name="ubound">Upper bound, larges index to include in sort</param>
 ///<param name="comparer">Object to compare collections elements and determine sort order</param>
 public static void InsertionSort(IList list, int lbound, int ubound, IComparer comparer)
 {
     for(int i=lbound + 1; i <= ubound; i++) {
         object item = list[i];
         if(comparer.Compare(item, list[i-1]) < 0) {
             //i is not in sorted order
             list.RemoveAt(i);
             SortedInsert(item, list, lbound, i-1, comparer);
         }
     }
 }
 public static void Sort(int[][] array, IComparer<int[]> compareArg)
 {
     for (int i = 0; i < array.GetLength(0) - 1; i++)
     {
         for (int j = i + 1; j < array.GetLength(0); j++)
         {
             if (compareArg.Compare(array[i], array[j]) > 0)
                 Swap(ref array[i], ref array[j]);
         }
     }
 }
        /// <summary>
        /// Utility method to perform appropriate comparisons with the given comparer. A10 should
        /// be less than B15 for all our tests
        /// </summary>
        static void TestComparisons(IComparer<NameAndNumber> comparer)
        {
            Assert.AreEqual(0, comparer.Compare(A10, A10));
            Assert.AreEqual(0, comparer.Compare(B15, B15));
            Assert.AreEqual(0, comparer.Compare(null, null));

            Assert.Less(comparer.Compare(null, A10), 0);
            Assert.Greater(comparer.Compare(A10, null), 0);

            Assert.Less(comparer.Compare(A10, B15), 0);
            Assert.Greater(comparer.Compare(B15, A10), 0);
        }
        public static void AreEqual(IComparer actual, IComparer expected, string message = null)
        {
            if (actual.Compare(actual, expected) != 0)
              {
            throw new Exception(@"Objects are different. Comment: {0}

            Actual: {1}
            Expect: {2}

            Log file: {3}".FormatWith(message, actual, expected, LogFilePath));
              }
        }
Exemple #21
0
        /// <inheritdoc />
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
        public int Compare(T x, T y)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
        {
            int parentResult = _parent?.Compare(x, y) ?? 0;

            if (x == null && y == null)
            {
                return(0);
            }

            return(parentResult != 0 ? parentResult : _inner(x, y));
        }
Exemple #22
0
 public static void BubbleSort(string[] array, IComparer<string> comparer)
 {
     for (int i = 1; i < array.Length; i++)
     {
         for (int j = 0; j < array.Length - 1; j++)
         {
             if (comparer.Compare(array[j], array[j+1]) > 0)
             {
                Swap(ref array[j],ref array[j+1]);
             }
         }
     }
 }
        public static int FindIndexStatistic( this int[] buffer, int index,
            int start, int count, IComparer<int> comparer)
        {
            if ( index < start || index >= start + count )
                throw new IndexOutOfRangeException();

            int statistic = 0;
            for ( int i = start; i < start + count; ++i )
                if ( comparer.Compare( buffer[i], buffer[index] ) < 0 )
                    ++statistic;

            return statistic;
        }
 private static void Sort(int[][] array, IComparer<int[]> comparer)
 {
     for (int i = array.Length - 1; i >= 0; i--)
     {
         for (int j = 0; j < i; j++)
         {
             if (comparer.Compare(array[j], array[j + 1]) == 1)
             {
                 SwapArray(ref array[j], ref array[j+1]);
             }
         }
     }
 }
Exemple #25
0
 /// <summary>
 /// Validates that the specified value is less than or equal to a specified compare
 /// value.
 /// </summary>
 /// <typeparam name="T">The type of the value being validated.</typeparam>
 /// <param name="value">The value to validate is less than or equal to the specified
 /// compare value.</param>
 /// <param name="compareValue">The compare value to validate against.</param>
 /// <param name="valueName">The name of the parameter being validated.</param>
 /// <param name="comparer">The comparer to use to compare the specified values.</param>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is greater than
 /// <paramref name="compareValue"/>.</exception>
 public static void IsLessThanOrEqualTo <T>(
     T value,
     T compareValue,
     string valueName,
     IComparer <T> comparer)
 {
     if (comparer?.Compare(value, compareValue) > 0)
     {
         throw new ArgumentOutOfRangeException(
                   valueName,
                   Invariant($"Value must be less than or equal to {compareValue}."));
     }
 }
 public static void SortArrayByDecrease(int[][] arr, IComparer compare)
 {
     for (int i = 0; i < arr.Length; i++)
     {
         for (int j = i + 1; j < arr.Length; j++)
         {
             if (compare.Compare(arr[i], arr[j]) == -1)
             {
                 Swap(ref arr[i], ref arr[j]);
             }
         }
     }
 }
Exemple #27
0
 /// <summary>
 /// Validates that the specified value is greater than a specified compare value.
 /// </summary>
 /// <typeparam name="T">The type of the value being validated.</typeparam>
 /// <param name="value">The value to validate is greater than the specified compare value.
 /// </param>
 /// <param name="compareValue">The compare value to validate against.</param>
 /// <param name="valueName">The name of the parameter being validated.</param>
 /// <param name="comparer">The comparer to use to compare the specified values.</param>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than or
 /// equal to <paramref name="compareValue"/>.</exception>
 public static void IsGreaterThan <T>(
     T value,
     T compareValue,
     string valueName,
     IComparer <T> comparer)
 {
     if (comparer?.Compare(value, compareValue) <= 0)
     {
         throw new ArgumentOutOfRangeException(
                   valueName,
                   Invariant($"Value must be greater than {compareValue}."));
     }
 }
Exemple #28
0
		public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement,
			string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager, IComparer<XmlNode> nodeOrderComparer)
		{
			//enhance: if the parent path isn't found, strip of the last piece and recurse,
			//so that the path will always be created if needed.

			XmlNode parentNode = node.SelectSingleNode(xpathNotIncludingElement,nameSpaceManager);
			if (parentNode == null)
			{
				throw new ApplicationException(string.Format("The path {0} could not be found", xpathNotIncludingElement));
			}
			string prefix = "";
			if (!String.IsNullOrEmpty(nameSpace))
			{
				prefix = nameSpace + ":";
			}
			XmlNode n = parentNode.SelectSingleNode(prefix+elementName,nameSpaceManager);
			if (n == null)
			{
				if (!String.IsNullOrEmpty(nameSpace))
				{
					n = GetDocument(node).CreateElement(nameSpace, elementName, nameSpaceManager.LookupNamespace(nameSpace));
				}
				else
				{
					n = GetDocument(node).CreateElement(elementName);
				}
				if (nodeOrderComparer == null)
				{
					parentNode.AppendChild(n);
				}
				else
				{
					XmlNode insertAfterNode = null;
					foreach (XmlNode childNode in parentNode.ChildNodes)
					{
						if (childNode.NodeType != XmlNodeType.Element)
						{
							continue;
						}
						if (nodeOrderComparer.Compare(n, childNode) < 0)
						{
							break;
						}
						insertAfterNode = childNode;
					}
					parentNode.InsertAfter(n, insertAfterNode);
				}
			}
			return n;
		}
 public static int Compare(SortedList a, SortedList b, IComparer comparer)
 {
     if (a == null || b == null) {
         return 1;
     }
     int cmp;
     int limit = (a.Count < b.Count) ? a.Count : b.Count;
     for(int i=0; i < limit; i++) {
         if(0 != (cmp = comparer.Compare(a.GetByIndex(i), b.GetByIndex(i)))) {
             return cmp;
         }
     }
     return a.Count - b.Count;
 }
Exemple #30
0
 // Stable insertion seort
 // TODO: Should really be merge sort
 public override void Sort(IComparer comparison)
 {
     if (comparison == null)
         throw new System.ArgumentNullException( "comparison" );
     int count = this.Count;
     for(int j = 1; j < count; j++) {
         object key = this[j];
         int i = j - 1;
         for (; i >= 0 && comparison.Compare(this[i], key) > 0; i--) {
             this[i + 1] = this[i];
         }
         this[i + 1] = key;
     }
 }
		/// <summary>
		/// Can the timestamped transaction re-cache this
		/// locked item now?
		/// </summary>
		public bool IsPuttable( long txTimestamp, object newVersion, IComparer comparator )
		{
			if( timeout < txTimestamp )
			{
				return true;
			}
			if( multiplicity > 0 )
			{
				return false;
			}
			return version == null ?
				unlockTimestamp < txTimestamp :
				comparator.Compare( version, newVersion ) < 0; //by requiring <, we rely on lock timeout in the case of an unsuccessful update!
		}
Exemple #32
0
    /// <summary>
    /// Asserts that the elements at the given index in both arrays are equal.
    /// </summary>
    /// <param name="comparer">An optional comparer to use.</param>
    public static void AssertArrayElementsAreEqual(Array first, Array second, int index, IComparer comparer = null)
    {
        object firstValue = first.GetValue(index);
        object secondValue = second.GetValue(index);

        if (comparer != null)
        {
            Assert.Equal(0, comparer.Compare(firstValue, secondValue));
        }
        else
        {
            Assert.Equal(firstValue, secondValue);
        }
    }
Exemple #33
0
        public static String[] BubbleSort(String[] sourceArray, IComparer<String> Comparer)
        {
            for (int i = 0; i < sourceArray.Length; i++)
            {
                for (int j = i + 1; j < sourceArray.Length; j++)
                {

                    if (Comparer.Compare(sourceArray[j],sourceArray[i])==-1)
                    {
                        swap(sourceArray,i,j);
                    }
                }
            }
            return sourceArray;
        }
Exemple #34
0
 //public static bool CheckMass(int[][] m)
 //{
 //    bool b=true;
 //    if (m == null || m.Length == 0)
 //        b = false;
 //    else{
 //        for (int i = 0; i < m.Length; i++)
 //        {
 //            if (m[i] == null || m[i].Length == 0)
 //                b = false;
 //        }
 //    }
 //    return b;
 //}
 public static void Sort(int[][] m, IComparer<int[]> comparer)
 {
     if (m == null || comparer == null)
     {
         throw new ArgumentNullException();
     }
     for (int i = 0; i < m.GetLength(0)-1; i++)
     {
         for (int j = i + 1; j < m.GetLength(0); j++)
         {
             if( comparer.Compare( m[i], m[j] ) > 1)
                 Swap(ref m[i],ref m[j]);
         }
     }
 }
        public static void Sort(int[][] array, IComparer<int[]> comparer)
        {
            int iEnd = array.Length - 1;

            while (0 < iEnd)
            {
                for (int j = 0; j < iEnd; j++)
                    if (comparer.Compare(array[j], array[j + 1]) > 0)
                    {
                        int[] a = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = a;
                    } 
                iEnd--;
            }
        }
 public static int Compare(IList a, IList b, IComparer comparer)
 {
     if (a == null || b == null) {
         return 1;
     }
     int limit = (a.Count < b.Count) ? a.Count : b.Count;
     for(int i=0; i < limit; i++) {
         if (a[i] is IComparable && b[i] is IComparable) {
             int cmp = comparer.Compare(a[i], b[i]);
             if (cmp != 0) {
                 return cmp;
             }
         }
     }
     return a.Count - b.Count;
 }
        public static void SortArray(int[][] arr, IComparer comparer)
        {
            if (comparer == null || arr == null)
                throw new ArgumentNullException();

            for (int i = 0; i < arr.Length; i++)
            {
                for (int j = i + 1; j < arr.Length; j++)
                {
                    if (comparer.Compare(arr[i], arr[j]) == -1)
                    {
                        Swap(ref arr[i], ref arr[j]);
                    }
                }
            }
        }
Exemple #38
0
        /**********************************************************************/
        #region Constructors

        /// <summary>
        /// Construct a new pair from the given min and max values.
        /// </summary>
        /// <param name="min">The minimum value of the new range.</param>
        /// <param name="max">The maximum value of the new range.</param>
        /// <param name="comparer">
        /// The comparer to be used for comparing the minimum and maximum values.
        /// <see cref="Comparer{T}.Default"/> is used if null is given.
        /// </param>
        /// <exception cref="ArgumentException">Throws if min is greater than max</exception>
        public MinMaxPair(T min, T max, IComparer <T> comparer = null)
        {
            var comparison = comparer?.Compare(min, max) ?? Comparer <T> .Default.Compare(min, max);

            if (comparison > 0)
            {
                throw new ArgumentOutOfRangeException(nameof(max), max, $"Cannot be less than {nameof(min)}");
            }

            Min     = min;
            Max     = max;
            IsRange = comparison != 0;

            _comparer = comparer;

            _hashCode = CalculateHashCode(min, max);
        }
 public int Compare(BenchmarkCase x, BenchmarkCase y)
 {
     if (x == null && y == null)
     {
         return(0);
     }
     if (x != null && y == null)
     {
         return(1);
     }
     if (x == null)
     {
         return(-1);
     }
     return(new[]
     {
         paramsComparer?.Compare(x.Parameters, y.Parameters) ?? 0,
         jobComparer?.Compare(x.Job, y.Job) ?? 0,
         targetComparer?.Compare(x.Descriptor, y.Descriptor) ?? 0,
         string.CompareOrdinal(x.DisplayInfo, y.DisplayInfo)
     }.FirstOrDefault(c => c != 0));
 }
Exemple #40
0
 private int Compare(T x, T y)
 {
     return(_comparer?.Compare(x, y) ?? x.CompareTo(y));
 }
Exemple #41
0
 public int CompareTo(Node <T> other)
 {
     return(comparer?.Compare(Data, other.Data)
            ?? Data.CompareTo(other.Data));
 }
Exemple #42
0
 int IComparer <KeyValuePair <TKey, TValue> > .Compare(KeyValuePair <TKey, TValue> x, KeyValuePair <TKey, TValue> y)
 {
     return(_comparer.Compare(x.Key, y.Key));
 }
 /// <summary>
 /// Determines if the values are equal.
 /// </summary>
 /// <returns>
 /// <c>true</c> if first is equals to the second; otherwise, <c>false</c>.
 /// </returns>
 /// <param name="first">The first value.</param>
 /// <param name="second">The second value.</param>
 /// <param name="comparer"></param>
 /// <typeparam name="T">The Type of values.</typeparam>
 public static bool IsEqualTo <T>(this T first, T second, IComparer <T> comparer = null)
     where T : IComparable <T>
 {
     return((comparer?.Compare(first, second) ?? first.CompareTo(second)) == 0);
 }
Exemple #44
0
 public PriorityQueue(IComparer <T> comp) : this((x, y) => comp.Compare(x, y))
 {
 }
 public static bool IsLessThanOrEqualTo <T>(this T first, T second, IComparer <T> comparer)
     where T : IComparable <T>
 {
     return((comparer?.Compare(first, second) ?? first.CompareTo(second)) <= 0);
 }
 public static bool IsGreaterThan <T>(this T first, T second, IComparer <T> comparer)
     where T : IComparable <T>
 {
     return((comparer?.Compare(first, second) ?? first.CompareTo(second)) > 0);
 }
Exemple #47
0
 /// <summary>
 /// Converts a <see cref="IComparer{T}"/> to a <see cref="IEqualityComparer{T}"/>.
 /// </summary>
 /// <typeparam name="T">The type being compared.</typeparam>
 /// <param name="comparer">The comparer.</param>
 /// <returns></returns>
 public static IEqualityComparer <T> ToEqualityComparer <T>(this IComparer <T> comparer)
 {
     return(new FunctorEqualityComparer <T>((x, y) => comparer.Compare(x, y) == 0));
 }
Exemple #48
0
 // Method for comparing keys using the provided comparer.
 private int CompareWithComparer(object x, object y)
 {
     return(comparer.Compare(x, y));
 }
Exemple #49
0
 public int Compare(EmbeddedPointerIndirectionNode <TTarget> x, EmbeddedPointerIndirectionNode <TTarget> y)
 {
     return(_innerComparer.Compare(x.Target, y.Target));
 }
Exemple #50
0
        /// <summary>
        /// Adds a new item to the list, inserting it in its corret position.
        /// </summary>
        /// <param name="item">The item to insert</param>
        public void Insert(T item)
        {
            int lower = 0;
            int upper = _elements.Count - 1;

            while (lower <= upper)
            {
                int middle           = lower + (upper - lower) / 2;
                int comparisonResult = _comparer == null?_comparisonFunction(item, _elements[middle]) : _comparer.Compare(item, _elements[middle]);

                if (comparisonResult == 0)
                {
                    _elements.Insert(middle, item);
                    return;
                }

                if (comparisonResult < 0)
                {
                    upper = middle - 1;
                }
                else
                {
                    lower = middle + 1;
                }
            }

            _elements.Insert(lower, item);
        }
            //---------------------------------------------------------------------------------------
            // Straightforward IEnumerator<T> methods.
            //

            internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
            {
                Contract.Assert(m_source != null);

                if (m_alreadySearched)
                {
                    return(false);
                }

                // Look for the greatest element.
                TSource candidate      = default(TSource);
                TKey    candidateKey   = default(TKey);
                bool    candidateFound = false;

                try
                {
                    int     loopCount = 0; //counter to help with cancellation
                    TSource value     = default(TSource);
                    TKey    key       = default(TKey);
                    while (m_source.MoveNext(ref value, ref key))
                    {
                        if ((loopCount & CancellationState.POLL_INTERVAL) == 0)
                        {
                            CancellationState.ThrowIfCanceled(m_cancellationToken);
                        }

                        // If the predicate is null or the current element satisfies it, we will remember
                        // it as the current partition's candidate for the last element, and move on.
                        if (m_predicate == null || m_predicate(value))
                        {
                            candidate      = value;
                            candidateKey   = key;
                            candidateFound = true;
                        }

                        loopCount++;
                    }

                    // If we found a candidate element, try to publish it, so long as it's greater.
                    if (candidateFound)
                    {
                        lock (m_operatorState)
                        {
                            if (m_operatorState.m_partitionId == -1 || m_keyComparer.Compare(candidateKey, m_operatorState.m_key) > 0)
                            {
                                m_operatorState.m_partitionId = m_partitionId;
                                m_operatorState.m_key         = candidateKey;
                            }
                        }
                    }
                }
                finally
                {
                    // No matter whether we exit due to an exception or normal completion, we must ensure
                    // that we signal other partitions that we have completed.  Otherwise, we can cause deadlocks.
                    m_sharedBarrier.Signal();
                }

                m_alreadySearched = true;

                // Only if we have a candidate do we wait.
                if (m_partitionId == m_operatorState.m_partitionId)
                {
                    m_sharedBarrier.Wait(m_cancellationToken);

                    // Now re-read the shared index. If it's the same as ours, we won and return true.
                    if (m_operatorState.m_partitionId == m_partitionId)
                    {
                        currentElement = candidate;
                        currentKey     = 0; // 1st (and only) element, so we hardcode the output index to 0.
                        return(true);
                    }
                }

                // If we got here, we didn't win. Return false.
                return(false);
            }
Exemple #52
0
 /// <summary>
 /// Compare left and right values
 /// </summary>
 /// <param name="left">The left value.</param>
 /// <param name="right">The right value.</param>
 /// <returns>Return a value indicating which value is larger.</returns>
 private int Compare(TScore left, TScore right)
 {
     return(comparer?.Compare(left, right) ?? left.CompareTo(right));
 }
Exemple #53
0
        public bool Remove(KeyValuePair <TKey, TValue> item)
        {
            if (root == null)
            {
                return(false);
            }
            lock (this)
            {
                var  key  = item.Key;
                Node prev = null;
                var  c    = root;
                stack.Clear();
                do
                {
                    var cmp = comparer?.Compare(key, c.key) ?? key.CompareTo(c.key);
                    if (cmp == 0)
                    {
                        if (!item.Value.Equals(c.value))
                        {
                            return(false);
                        }
                        if (c.greater == null)
                        {
                            if (prev == null)
                            {
                                root = c.less;
                            }
                            else
                            {
                                if (prev.greater == c)
                                {
                                    prev.greater = c.less;
                                }
                                else
                                {
                                    prev.less = c.less;
                                }
                            }
                        }
                        else if (c.less == null)
                        {
                            if (prev == null)
                            {
                                root = c.greater;
                            }
                            else
                            {
                                if (prev.greater == c)
                                {
                                    prev.greater = c.greater;
                                }
                                else
                                {
                                    prev.less = c.greater;
                                }
                            }
                        }
                        else
                        {
                            var caret = c.less;
                            if (caret.greater != null)
                            {
                                caret.height = 0;
                                var pcaret = c;
                                while (caret.greater != null)
                                {
                                    pcaret       = caret;
                                    caret        = caret.greater;
                                    caret.height = 0;
                                }
                                pcaret.greater = caret.less;
                                caret.greater  = c.greater;
                                caret.less     = c.less;
                                if (prev == null)
                                {
                                    root = caret;
                                }
                                else if (prev.greater == c)
                                {
                                    prev.greater = caret;
                                }
                                else
                                {
                                    prev.less = caret;
                                }
                            }
                            else
                            {
                                caret.height  = 0;
                                caret.greater = c.greater;
                                if (prev == null)
                                {
                                    root = caret;
                                }
                                else if (prev.greater == c)
                                {
                                    prev.greater = caret;
                                }
                                else
                                {
                                    prev.less = caret;
                                }
                            }
                        }
                        while (stack.Count > 0)
                        {
                            stack.Pop().height = 0;
                        }
                        root.Balance(ref root);
                        return(true);
                    }

                    if (cmp > 0)
                    {
                        if (c.greater == null)
                        {
                            return(false);
                        }
                        prev = c;
                        stack.Push(c);
                        c = c.greater;
                    }
                    else
                    {
                        if (c.less == null)
                        {
                            return(false);
                        }
                        prev = c;
                        stack.Push(c);
                        c = c.less;
                    }
                }while (true);
            }
        }
Exemple #54
0
 /// <summary>
 /// Compares two objects and returns a value indicating whether one is
 /// less than, equal to, or greater than the other.
 /// </summary>
 /// <returns>
 /// Value Condition Less than zero<paramref name="x" /> is less than
 /// <paramref name="y" />.Zero<paramref name="x" /> equals
 /// <paramref name="y" />.Greater than zero<paramref name="x" /> is
 /// greater than <paramref name="y" />.
 /// </returns>
 /// <param name="x">The first object to compare.</param>
 /// <param name="y">The second object to compare.</param>
 public int Compare(T x, T y)
 {
     return(-_baseComparer.Compare(x, y));
 }
        private static int?TryGetDesiredIndexIfGroupedWorker <TDeclarationSyntax>(
            SyntaxList <TDeclarationSyntax> declarationList,
            TDeclarationSyntax declaration,
            IList <bool> availableIndices,
            IComparer <TDeclarationSyntax> comparerWithoutNameCheck,
            IComparer <TDeclarationSyntax> comparerWithNameCheck)
            where TDeclarationSyntax : SyntaxNode
        {
            if (!declarationList.IsSorted(comparerWithoutNameCheck))
            {
                // Existing declarations weren't grouped.  Don't try to find a location
                // to this declaration into.
                return(null);
            }

            // The list was grouped (by type, staticness, accessibility).  Try to find a location
            // to put the new declaration into.

            var result            = Array.BinarySearch(declarationList.ToArray(), declaration, comparerWithoutNameCheck);
            var desiredGroupIndex = result < 0 ? ~result : result;

            Debug.Assert(desiredGroupIndex >= 0);
            Debug.Assert(desiredGroupIndex <= declarationList.Count);

            // Now, walk forward until we hit the last member of this group.
            while (desiredGroupIndex < declarationList.Count)
            {
                // Stop walking forward if we hit an unavailable index.
                if (availableIndices != null && !availableIndices[desiredGroupIndex])
                {
                    break;
                }

                if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[desiredGroupIndex]))
                {
                    // Found the index of an item not of our group.
                    break;
                }

                desiredGroupIndex++;
            }

            // Now, walk backward until we find the last member with the same name
            // as us.  We want to keep overloads together, so we'll place ourselves
            // after that member.
            var currentIndex = desiredGroupIndex;

            while (currentIndex > 0)
            {
                var previousIndex = currentIndex - 1;

                // Stop walking backward if we hit an unavailable index.
                if (availableIndices != null && !availableIndices[previousIndex])
                {
                    break;
                }

                if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[previousIndex]))
                {
                    // Hit the previous group of items.
                    break;
                }

                // Still in the same group.  If we find something with the same name
                // then place ourselves after it.
                if (0 == comparerWithNameCheck.Compare(declaration, declarationList[previousIndex]))
                {
                    // Found something with the same name.  Generate after this item.
                    return(currentIndex);
                }

                currentIndex--;
            }

            // Couldn't find anything with our name.  Just place us at the end of this group.
            return(desiredGroupIndex);
        }
 protected override bool CanReplace(T replaced, T replacing) =>
 (_valueComparer?.Compare(replacing, replaced) ?? 1) >= 0;     // allow replacing only if new value is >= old value
Exemple #57
0
 public PriorityQueue(IComparer <T> comp, int capacity) : this((x, y) => comp.Compare(x, y), capacity)
 {
 }
 protected int Compare(T x, T y)
 {
     return(_comparer?.Compare(x, y) ?? x.CompareTo(y));
 }
        /// <inheritdoc />
        public int Compare(T x, T y)
        {
            var parentResult = _parent?.Compare(x, y) ?? 0;

            return(parentResult != 0 ? parentResult : _inner(x, y));
        }
Exemple #60
0
 protected virtual int OnCompare(int i, int j)
 {
     return(mComparer.Compare(InnerList[i], InnerList[j]));
 }