상속: IComparer, IComparer
예제 #1
0
        public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
        {
            var comparer = new CustomComparer <T>(sortDirection, Comparer <T> .Default);

            var k = array.Length / 2;
            var j = 0;

            while (k >= 1)
            {
                for (int i = k; i < array.Length; i = i + k, j = j + k)
                {
                    if (comparer.Compare(array[i], array[j]) >= 0)
                    {
                        continue;
                    }

                    swap(array, i, j);

                    if (i <= k)
                    {
                        continue;
                    }

                    i -= k * 2;
                    j -= k * 2;
                }

                j  = 0;
                k /= 2;
            }

            return(array);
        }
예제 #2
0
        private static IList <TypeInfo <T> > findTypes <T>(string name) where T : IHasTypeNameDescription
        {
            var infos = new List <TypeInfo <T> >();

            foreach (var type in Assembly.GetEntryAssembly().GetTypes().Where(t => typeof(T).IsAssignableFrom(t) && !t.IsAbstract))
            {
                var constructor = type.GetConstructor(new Type[0]);
                if (constructor == null)
                {
                    // (the error message will only be seen by maker developers, so it's ok that it's shown before any UI appears)
                    DlgMessage.ShowWarning("Ignored {1} type \"{0}\" because it does not have a public parameterless constructor.".Fmt(type, name));
                }
                else
                {
                    infos.Add(new TypeInfo <T>
                    {
                        Type        = type,
                        Constructor = () => (T)constructor.Invoke(new object[0]),
                        Name        = type.Name,
                        Description = type.FullName,
                    });
                }
            }
            infos.Sort(CustomComparer <TypeInfo <T> > .By(ti => ti.Name));
            return(infos.AsReadOnly());
        }
예제 #3
0
        private static Dictionary <Type, SortedDictionary <Type, Delegate> > FindAllGenerators()
        {
            var result     = new Dictionary <Type, SortedDictionary <Type, Delegate> >();
            var generators = TypeDiscoverer.GetAllTypes()
                             .SelectMany(t => t.GetMethods())
                             .Where(IsGeneratorMethod)
                             .Select(GetGenerators);
            var typeComparer = new CustomComparer <Type>
                               (
                (left, right) => string.Compare(left.Name, right.Name, StringComparison.Ordinal)
                               );

            foreach (var(returnType, generatorType, @delegate) in generators)
            {
                if (@delegate == null)
                {
                    continue;
                }

                if (result.TryGetValue(returnType, out var dictionary))
                {
                    dictionary.TryAdd(generatorType, @delegate);
                }
                else
                {
                    dictionary = new SortedDictionary <Type, Delegate>(typeComparer)
                    {
                        { generatorType, @delegate }
                    };
                    result.Add(returnType, dictionary);
                }
            }

            return(result);
        }
예제 #4
0
 private void postLoad(List <Game> games)
 {
     games.Sort(CustomComparer <Game> .By(g => g.DateUtc));
     Games     = games.AsReadOnly();
     Name      = Games.Last().Plr(SummonerId).Name;
     PastNames = Games.Select(g => g.Plr(SummonerId).Name).ToList().AsReadOnly();
 }
예제 #5
0
        public void PriorityQueueStabilityTest()
        {
            CustomComparer <int>     comparer = new CustomComparer <int>((a, b) => Comparer <int> .Default.Compare(a / 10, b / 10));
            PriorityQueue <int, int> queue    = new PriorityQueue <int, int>(comparer);
            List <int> list   = new List <int>();
            Random     random = new Random();

            for (int i = 0; i < 100; i++)
            {
                int n = random.Next(100);

                int j = 0;
                while (j < list.Count && comparer.Compare(list[j], n) != 1)
                {
                    j++;
                }

                list.Insert(j, n);
                queue.Enqueue(n, n);
            }

            for (int i = 0; i < list.Count; i++)
            {
                int n = queue.Dequeue();
                Assert.AreEqual(list[i], n);
            }
        }
예제 #6
0
        public IOrderedEnumerable <TElement> CreateOrderedEnumerable <TNewKey>(Func <TElement, TNewKey> keySelector, IComparer <TNewKey> comparer, bool descending)
        {
            if (keySelector == null)
            {
                throw new ArgumentNullException(nameof(keySelector));
            }

            comparer = comparer ?? Comparer <TNewKey> .Default;
            if (descending)
            {
                comparer = comparer.Reverse();
            }

            var compoundComparer = new CustomComparer <KeyValuePair <TKey, TNewKey> >(Compare);

            return(new OrderedEnumerable <TElement, KeyValuePair <TKey, TNewKey> >(_source, CompoundKeySelector, compoundComparer));

            KeyValuePair <TKey, TNewKey> CompoundKeySelector(TElement item)
            {
                return(new KeyValuePair <TKey, TNewKey>(_keySelector(item), keySelector(item)));
            }

            int Compare(KeyValuePair <TKey, TNewKey> x, KeyValuePair <TKey, TNewKey> y)
            {
                var check = _comparer.Compare(x.Key, y.Key);

                return(check == 0 ? comparer.Compare(x.Value, y.Value) : check);
            }
        }
예제 #7
0
        public void CustomObjectScenarioShouldFail()
        {
            var customA = new Custom {
                Val = 1
            };
            var customB = new Custom {
                Val = 2
            };
            var comparer = new CustomComparer <Custom>();

            Verify.ShouldFail(() =>
                              customA.ShouldBeGreaterThanOrEqualTo(customB, comparer, "Some additional context"),

                              errorWithSource:
                              @"customA
    should be greater than or equal to
Shouldly.Tests.TestHelpers.Custom (000000)
    but was
Shouldly.Tests.TestHelpers.Custom (000000)

Additional Info:
    Some additional context",

                              errorWithoutSource:
                              @"Shouldly.Tests.TestHelpers.Custom (000000)
    should be greater than or equal to
Shouldly.Tests.TestHelpers.Custom (000000)
    but was not

Additional Info:
    Some additional context"
                              );
        }
예제 #8
0
        public static void VictoryFlash(Board board, Dictionary <int, int> winningMoveValues, bool playerOnesTurn)
        {
            var winningPositions =
                winningMoveValues.Select(positionValue => new BoardPosition(positionValue.Key, positionValue.Value))
                .ToList();

            for (int i = 0; i < 6; i++)
            {
                foreach (var position in winningPositions)
                {
                    if (playerOnesTurn)
                    {
                        ReplaceHistory(board.BoardHistory, position,
                                       CustomComparer.PositionHistoryCompare(board.BoardHistory, position,
                                                                             PositionHistory.Player1Piece)
                                ? PositionHistory.Player1PieceHighlighted
                                : PositionHistory.Player1Piece);
                    }
                    else
                    {
                        ReplaceHistory(board.BoardHistory, position,
                                       CustomComparer.PositionHistoryCompare(board.BoardHistory, position,
                                                                             PositionHistory.Player2Piece)
                                ? PositionHistory.Player2PieceHighlighted
                                : PositionHistory.Player2Piece);
                    }
                }
                BoardUI.DisplayGameBoard(board);
                System.Threading.Thread.Sleep(300);
                Console.Clear();
            }

            BoardUI.DisplayGameBoard(board);
        }
예제 #9
0
        public SortableBindingList(IEnumerable <Tuple <string, ListSortDirection> > props, List <T> list)
            : base(list)
        {
            // Build Comparer chain
            var t = TypeDescriptor.GetProperties(typeof(T));

            foreach (var prop in props)
            {
                var p = t.Find(prop.Item1, false);
                if (p == null)
                {
                    throw new ArgumentException("The property \"" + prop.Item1 + "\" was not found on " + typeof(T).FullName + ".", "prop");
                }

                isSorted = true;
                this.propertyDescriptor = p;
                this.listSortDirection  = prop.Item2;
                this.comparer           = new CustomComparer(this.comparer, p, prop.Item2);
            }

            // Wrap in final Comparer for user sorting
            this.comparer = new CustomComparer(this.comparer);

            var items = this.Items as List <T>;

            items.Sort(this.comparer);
        }
예제 #10
0
 public CustomComparer(CustomComparer baseComparer, PropertyDescriptor prop = null, ListSortDirection direction = ListSortDirection.Ascending)
 {
     _baseComparer = baseComparer;
     Direction     = direction;
     Property      = prop;
     _comparer     = GetComparer(prop);
 }
예제 #11
0
 public void ShouldPass()
 {
     var customA = new Custom { Val = 1 };
     var customB = new Custom { Val = 1 };
     var comparer = new CustomComparer<Custom>();
     customA.ShouldBeGreaterThanOrEqualTo(customB, comparer);
 }
예제 #12
0
        public void CustomObjectScenarioShouldFail()
        {
            var customA = new Custom { Val = 1 };
            var customB = new Custom { Val = 2 };
            var comparer = new CustomComparer<Custom>();
            Verify.ShouldFail(() =>
            customA.ShouldBeGreaterThanOrEqualTo(customB, comparer, "Some additional context"),

            errorWithSource:
            @"customA
            should be greater than or equal to
            Shouldly.Tests.TestHelpers.Custom (000000)
            but was
            Shouldly.Tests.TestHelpers.Custom (000000)

            Additional Info:
            Some additional context",

            errorWithoutSource:
            @"Shouldly.Tests.TestHelpers.Custom (000000)
            should be greater than or equal to
            Shouldly.Tests.TestHelpers.Custom (000000)
            but was not

            Additional Info:
            Some additional context"
            );
        }
예제 #13
0
 public CustomComparer(CustomComparer baseComparer, PropertyDescriptor prop, ListSortDirection direction)
 {
     this.baseComparer = baseComparer;
     this.Direction    = direction;
     this.Property     = prop;
     this.comparer     = GetComparer(prop);
 }
예제 #14
0
파일: Selection.cs 프로젝트: kahili7/ntmath
        public static T[] Distinct <T, TProperty>(this T[] values, Func <T, TProperty> property) where TProperty : IComparable <TProperty>
        {
            CustomComparer <T> comparer = new CustomComparer <T>((a, b) => property(a).CompareTo(property(b)));

            var set = new HashSet <T>(values, comparer);

            return(set.ToArray());
        }
예제 #15
0
        public static IComparer <T1, T2> ToComparer <T1, T2>([NotNull] this Func <T1, T2, Int32> comparison)
        {
            if (comparison is null)
            {
                throw new ArgumentNullException(nameof(comparison));
            }

            return(CustomComparer.Create(comparison));
        }
예제 #16
0
        public void ExplicitComparer()
        {
            var cmp = new CustomComparer <int>();
            var hs  = Enumerable.Range(0, 50).ToHashSet(cmp);

            Assert.IsType <HashSet <int> >(hs);
            Assert.Equal(50, hs.Count);
            Assert.Same(cmp, hs.Comparer);
        }
예제 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtHashSet{T}"/> class.
        /// </summary>
        /// <param name="elements">The initial elements in the set.</param>
        /// <param name="comparer">The equality comparer to use; or <see langword="null"/> to use the default comparer.</param>
        public ExtHashSet(IEnumerable <T> elements, IEqualityComparer <T> comparer)
        {
            // NOTE: We want to encourage the use of the appropriate overloads
            // instead of explicitly allowing users to call these constructors with null arguments,
            // but we don't want to forbid null either as it allows us to gather all the
            // constructor logic in one place.

            var innerComparer = new CustomComparer(comparer ?? EqualityComparer <T> .Default);

            this.innerSet = elements != null ? new HashSet <T>(elements, innerComparer) : new HashSet <T>(innerComparer);
        }
예제 #18
0
        public void ShouldPass()
        {
            Custom customA = new Custom {
                Val = 1
            };
            Custom customB = new Custom {
                Val = 1
            };
            var comparer = new CustomComparer <Custom>();

            customA.ShouldBeLessThanOrEqualTo(customB, comparer);
        }
예제 #19
0
        public void ShouldPass()
        {
            var customA = new Custom {
                Val = 1
            };
            var customB = new Custom {
                Val = 1
            };
            var comparer = new CustomComparer <Custom>();

            customA.ShouldBeGreaterThanOrEqualTo(customB, comparer);
        }
예제 #20
0
        public void ShouldPass()
        {
            var customA = new Custom {
                Val = 2
            };
            var customB = new Custom {
                Val = 1
            };
            var comparer = new CustomComparer <Custom>();

            customB.ShouldBeLessThan(customA, comparer);
        }
예제 #21
0
        public void ToDictionary_PassCustomComparer()
        {
            CustomComparer <int> comparer   = new CustomComparer <int>();
            TestCollection <int> collection = new TestCollection <int>(new int[] { 1, 2, 3, 4, 5, 6 });

            Dictionary <int, int> result1 = collection.ToDictionary(key => key, comparer);

            Assert.Same(comparer, result1.Comparer);

            Dictionary <int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);

            Assert.Same(comparer, result2.Comparer);
        }
예제 #22
0
        public void ToDictionary_UseDefaultComparerOnNull()
        {
            CustomComparer <int> comparer   = null;
            TestCollection <int> collection = new TestCollection <int>(new int[] { 1, 2, 3, 4, 5, 6 });

            Dictionary <int, int> result1 = collection.ToDictionary(key => key, comparer);

            Assert.Same(EqualityComparer <int> .Default, result1.Comparer);

            Dictionary <int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);

            Assert.Same(EqualityComparer <int> .Default, result2.Comparer);
        }
예제 #23
0
        /// <summary>
        /// Time complexity: O(n^2)
        /// </summary>
        public static Span <T> Sort(Span <T> array, SortDirection sortDirection = SortDirection.Ascending)
        {
            if (array.Length <= 1)
            {
                return(array);
            }

            var comparer = new CustomComparer <T>(sortDirection, Comparer <T> .Default);

            sort(array, 0, array.Length - 1, comparer);

            return(array);
        }
예제 #24
0
        /// <summary>
        /// Merge two sorted arrays.
        /// </summary>
        private static void merge(Indexable <T> array, int leftStart, int middle, int rightEnd,
                                  CustomComparer <T> comparer)
        {
            var newLength = rightEnd - leftStart + 1;

            var result = new T[newLength];

            int i = leftStart, j = middle + 1, k = 0;

            //iteratively compare and pick min to result
            while (i <= middle && j <= rightEnd)
            {
                if (comparer.Compare(array[i], array[j]) < 0)
                {
                    result[k] = array[i];
                    i++;
                }
                else
                {
                    result[k] = array[j];
                    j++;
                }
                k++;
            }

            //copy left overs
            if (i <= middle)
            {
                for (var l = i; l <= middle; l++)
                {
                    result[k] = array[l];
                    k++;
                }
            }
            else
            {
                for (var l = j; l <= rightEnd; l++)
                {
                    result[k] = array[l];
                    k++;
                }
            }

            k = 0;
            //now write back result
            for (var g = leftStart; g <= rightEnd; g++)
            {
                array[g] = result[k];
                k++;
            }
        }
예제 #25
0
        public void CustomComparerTest_For2EqualObjects_ReturnsEquality()
        {
            var car1 = new Car {
                Id = 1, Brand = "Audi", Model = "A8", Year = 2010
            };

            var car2 = new Car {
                Id = 1, Brand = "Audi", Model = "A8", Year = 2010
            };

            var comparer = new CustomComparer <Car>();

            Assert.IsTrue(comparer.Equals(car1, car2));
        }
예제 #26
0
        public void CustomComparerTest_For2NonEqualObjects_ReturnsInequality()
        {
            var car1 = new Car {
                Id = 2, Brand = "Mercedes", Model = "C200", Year = 2012
            };

            var car2 = new Car {
                Id = 2, Brand = "Mercedes", Model = "E320", Year = 2012
            };

            var comparer = new CustomComparer <Car>();

            Assert.IsFalse(comparer.Equals(car1, car2));
        }
예제 #27
0
        internal static void PartitionMerge(Indexable <T> array, int leftIndex, int rightIndex,
                                            CustomComparer <T> comparer)
        {
            if (leftIndex < 0 || rightIndex < 0 || (rightIndex - leftIndex + 1) < 2)
            {
                return;
            }

            var middle = (leftIndex + rightIndex) / 2;

            PartitionMerge(array, leftIndex, middle, comparer);
            PartitionMerge(array, middle + 1, rightIndex, comparer);

            merge(array, leftIndex, middle, rightIndex, comparer);
        }
        public static string LargestNum(List <int> input)
        {
            List <string> strInput = new List <string>();

            foreach (var item in input)
            {
                strInput.Add(item.ToString());
            }
            CustomComparer comparer = new CustomComparer();

            strInput.Sort(comparer);
            Console.WriteLine(String.Join("", strInput.ToArray()));
            strInput.Reverse();

            Console.WriteLine(String.Join("", strInput.ToArray()));
            return(String.Join("", strInput.ToArray()));
        }
예제 #29
0
    public Path ComputeInternalPathFromTo(Tile _StartTile, Tile _EndTile)
    {
        List <PathLinkHeuristic> openList = new List <PathLinkHeuristic>();
        HashSet <Tile>           closeSet = new HashSet <Tile>();

        openList.Add(new PathLinkHeuristic(_StartTile, Tile.GetManhattanDistance(_StartTile, _EndTile)));
        CustomComparer <PathLinkHeuristic> comparer = new CustomComparer <PathLinkHeuristic>(false);

        while (openList.Count > 0)
        {
            PathLinkHeuristic linkToExtend = openList.Last();
            if (linkToExtend.Tile == _EndTile)
            {
                return(Path.CreatePath(linkToExtend));
            }
            openList.RemoveAt(openList.Count - 1);
            Tile tileToExtend = linkToExtend.Tile;
            if (closeSet.Contains(tileToExtend))
            {
                continue;
            }

            closeSet.Add(tileToExtend);
            for (int i = 0; i < tileToExtend.Neighbors.Count; i++)
            {
                Tile neighbor = tileToExtend.Neighbors[i];
                if (!neighbor.IsAccessible || !IsTileInside(neighbor) || closeSet.Contains(neighbor))
                {
                    continue;
                }

                //PathLinkHeuristic extension = new PathLinkHeuristic(linkToExtend, neighbor, Tile.GetManhattanDistance(neighbor, _EndTile));
                PathLinkHeuristic extension = linkToExtend.MakeExtensionWith(neighbor, Tile.GetManhattanDistance(neighbor, _EndTile));
                int indexInsertion          = openList.BinarySearch(extension, comparer);
                if (indexInsertion < 0)
                {
                    indexInsertion = ~indexInsertion;
                }
                openList.Insert(indexInsertion, extension);
            }
        }

        return(null);
    }
예제 #30
0
        static EnumOf()
        {
            var type           = typeof(T);
            var underlyingType = type.GetEnumUnderlyingType();
            var compare        = CreateCompare(underlyingType);
            var equals         = CreateEquals(underlyingType);
            var getHashCode    = CreateGetHashCode(underlyingType);

            Attributes           = type.GetCustomAttributes <Attribute>().ToImmutableArray();
            Comparer             = new CustomComparer <T>(compare, equals, getHashCode);
            Handle               = type.TypeHandle;
            Flags                = Attributes.Any <FlagsAttribute>();
            Internal             = !type.IsVisible;
            Public               = type.IsPublic;
            Name                 = type.GetName();
            UnderlyingType       = type.GetSystemType();
            UnderlyingTypeHandle = underlyingType.TypeHandle;

            Tokens = type.GetFields(STATIC_BINDINGS).To(fieldInfo => new Token(fieldInfo)).ToImmutableDictionary(_ => _.Value, Comparer);
        }
예제 #31
0
        private static T medianOfMedian(T[] input, int left, int right)
        {
            if (left.CompareTo(right) == 0)
            {
                return(input[left]);
            }

            var comparer = new CustomComparer <T>(SortDirection.Ascending, Comparer <T> .Default);

            var size        = 5;
            var currentLeft = left;

            var medians     = new T[(right - left) / size + 1];
            var medianIndex = -1;

            while (currentLeft <= right)
            {
                var currentRight = currentLeft + size - 1;

                if (currentRight <= right)
                {
                    sort(input, currentLeft, currentRight, comparer);
                    medians[++medianIndex] = median(input, currentLeft, currentRight);
                }
                else
                {
                    sort(input, currentLeft, right, comparer);
                    medians[++medianIndex] = median(input, currentLeft, right);
                }

                currentLeft = currentRight + 1;
            }

            if (medians.Length == 1)
            {
                return(medians[0]);
            }

            return(medianOfMedian(medians, 0, medians.Length - 1));
        }
예제 #32
0
        /// <summary>
        ///   Used to create a Lambda Member Lookup based on Type and Specflow Table.
        ///   Resulting CustomComparer can be used in Collection Comparer and Fancy Printers
        /// </summary>
        private static CustomComparer <T> ComparerCreator <T>(Table table)
        {
            var contentComparer = CustomComparer <T> .CreateNew();

            for (var i = 0; i < table.Header.Count(); i++)
            {
                var propertyInfo = PropertyInfoHelper.GetCaseInsensitivePropertyInfo(typeof(T), table.Header.ElementAt(i));

                if (propertyInfo != null)
                {
                    // One dynamic property on the fly
                    var entityParam          = Expression.Parameter(typeof(T), "e");
                    var memberExpressionReal = Expression.MakeMemberAccess(entityParam, propertyInfo);
                    var memberExpressionObj  = Expression.Convert(memberExpressionReal, typeof(object));
                    var exp = Expression.Lambda <Func <T, object> >(memberExpressionObj, entityParam);

                    contentComparer.Add(exp);
                }
            }

            return(contentComparer);
        }
예제 #33
0
        public IEnumerable<Bunny> ListBunniesBySuffix(string suffix)
        {
            var customComparer = new CustomComparer();
            var result = new SortedDictionary<string, Bunny>(customComparer);
            foreach (var bunny in this.bunniesByName.Values)
            {
                if (bunny.Name.EndsWith(suffix))
                {
                    result.Add(ReverseName(bunny.Name), bunny);
                }
            }

            foreach (var item in result)
            {
                yield return item.Value;
            }
        }
예제 #34
0
 public void String_PreOrderTraversal_CustomComparerTest()
 {
     BinaryTree<string> bt = new BinaryTree<string>();
     CustomComparer<string> comparer = new CustomComparer<string>((str1,str2) => str1.CompareTo(str2)*(-1));
     bt.Comparer = comparer;
     string[] elemToAdd = { "f", "b", "a", "d", "c", "e", "i", "h", "g", "k", "j" };
     foreach (var item in elemToAdd)
         bt.Add(item);
     List<string> actual = new List<string>();
     foreach (var item in bt.Preorder())
     {
         actual.Add(item);
     }
     List<string> expected =
         new List<string>(new string[] { "f", "i", "k", "j", "h", "g", "b", "d", "e", "c", "a" });
     CollectionAssert.AreEqual(expected, actual);
 }