Example #1
0
        public FSA(string name, IEnumerable <FSATransition <TValue> > transitions, IEnumerable <int> q0, IEnumerable <int> f)
        {
            Name = name.ThrowIfEmpty();
            Q0   = q0.ToHashSet();
            F    = f.ToHashSet();

            #region Speedup
            foreach (var t in transitions)
            {
                OrderedSet <FSATransition <TValue> > predics;
                if (!_lookup.TryGetValue(t.BeginState, out predics))
                {
                    predics = new OrderedSet <FSATransition <TValue> >();
                    _lookup[t.BeginState] = predics;
                }
                predics.Add(t);

                if (!PredicateEdgeBase <TValue> .IsEpsilon(t.Condition))
                {
                    _sigma.Add(t.Condition);
                }
            }
            StateCount = Q.Count();
            #endregion
        }
        public void DirectRightAndLeftCheckExistingItem()
        {
            OrderedSet <int> tree = new OrderedSet <int>();

            tree.Add(10);
            tree.Add(-10);
            tree.Add(20);
            tree.Add(-20);

            OrderedSet <int> expectedOutputTree = new OrderedSet <int>();

            expectedOutputTree.Add(10);
            expectedOutputTree.Add(-10);
            expectedOutputTree.Add(20);
            expectedOutputTree.Add(-20);

            var outputRL         = tree.DirectRightAndLeft(10);
            var expectedOutputRL = new KeyValuePair <int, int>(20, -10);

            Assert.AreEqual(outputRL.Key, expectedOutputRL.Key, "Right element is incorrect");
            Assert.AreEqual(outputRL.Value, expectedOutputRL.Value, "Left element is incorrect");

            Assert.AreEqual(expectedOutputTree.Count, tree.Count, "Tree size is incorrect!");

            for (int i = 0; i < expectedOutputTree.Count; i++)
            {
                Assert.AreEqual(expectedOutputTree[i], tree[i], "Tree Element at index " + i + " is incorrect");
            }
        }
Example #3
0
		private void Tock (Object state)
		{
			List<IMinion> toDo = new List<IMinion> ();
			lock (this.capsules) {
				long t = tick++;
				if (capsules.Count == 0)
					return;
				ICapsule c = capsules.GetFirst ();
				IMinion m = c.GetReadiedMinion (t);
				while (m != null) {
					Console.WriteLine ("{0}\t Playing: {1}", t, m);
					capsules.Remove (c);
					if (t == 24) {
						Console.WriteLine ("----- Popped: {0} {1}", c.GetTicksToStart (), capsules);

					}
					if (!c.CanDispose ()) {
						// Sorted to the new start tick
						capsules.Add (c);
					}

					if (t == 24) {
						Console.WriteLine ("------ Reorg: {0} {1}", c.GetTicksToStart (), capsules);

					}
					toDo.Add (m);
					if (capsules.Count == 0)
						break;
					c = capsules.GetFirst ();
					m = c.GetReadiedMinion (t);
				}
			}
			//taskMaster.Invoke (toDo);
		}
Example #4
0
        static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            set.Remove(9);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(set.Contains(9));
            Console.WriteLine();
            set.Add(25);
            set.Add(25);
            set.Add(25);
            set.Add(25);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }
        }
Example #5
0
    public bool Initialize(Node _start, Node _goal)
    {
        if (!NodeManager.Instance.Contains(_start, _goal))
        {
            return(false);
        }

        start = _start;
        goal  = _goal;
        open.Clear();
        closed.Clear();
        foreach (List <Node> list in map)
        {
            foreach (Node node in list)
            {
                if (node != null)
                {
                    node.g      = float.MaxValue;
                    node.h      = Heuristic(node, goal);
                    node.parent = null;
                }
            }
        }
        start.g = 0f;
        start.CalcF();
        open.Add(start);
        return(true);
    }
 public ICollection <ConfigItem> Get(ConfigurationType typesToReturn)
 {
     lock (_lockObject)
     {
         OrderedSet <ConfigItem> list = new OrderedSet <ConfigItem>();
         foreach (ConfigItem item in _configItems.Values)
         {
             if (item.IsEditable)
             {
                 if ((typesToReturn & ConfigurationType.Global) == ConfigurationType.Global)
                 {
                     list.Add(new ConfigItem(item));
                 }
             }
             else
             {
                 if ((typesToReturn & ConfigurationType.System) == ConfigurationType.System)
                 {
                     list.Add(new ConfigItem(item));
                 }
             }
         }
         return(list);
     }
 }
Example #7
0
        private void HandleNeighbour(Face neighbour)
        {
            if (neighbour == null || (neighbour.AreaMask & agentAreaMask) == 0 || closeSet.Contains(neighbour))
            {
                return;
            }
            var neighbourCenter = neighbour.CalculateCenter();

            float neighbourDistance          = Vector3.Distance(currentCenter, neighbourCenter);
            float neighbourDistanceCostBonus = (neighbour.Weight * neighbourDistance - neighbourDistance) / 2;

            float possibleGCost = current.gCost + neighbourDistance + neighbourDistanceCostBonus;

            var neighbourSetElement = openSet.BruteFind((e) => e.face == neighbour);

            if (neighbourSetElement == null)
            {
                openSet.Add(new FaceStarUnit(neighbour, current, possibleGCost, Vector3.Distance(neighbourCenter, endCenter) + neighbourDistanceCostBonus));
            }
            else if (possibleGCost < neighbourSetElement.gCost)
            {
                openSet.Remove(neighbourSetElement);
                neighbourSetElement.Update(current, possibleGCost, Vector3.Distance(neighbourCenter, endCenter) + neighbourDistanceCostBonus);
                openSet.Add(neighbourSetElement);
            }
        }
        public void DirectRightAndLeftCheckExistingObject()
        {
            OrderedSet <ClassTester> tree = new OrderedSet <ClassTester>((x, y) => { return(x.compareByValue.CompareTo(y.compareByValue)); });

            tree.Add(new ClassTester(10, 2));
            tree.Add(new ClassTester(-10, 1));
            tree.Add(new ClassTester(20, 3));
            tree.Add(new ClassTester(-20, 0));

            OrderedSet <ClassTester> expectedOutputTree = new OrderedSet <ClassTester>((x, y) => { return(x.compareByValue.CompareTo(y.compareByValue)); });

            expectedOutputTree.Add(new ClassTester(10, 2));
            expectedOutputTree.Add(new ClassTester(-10, 1));
            expectedOutputTree.Add(new ClassTester(20, 3));
            expectedOutputTree.Add(new ClassTester(-20, 0));

            var outputRL         = tree.DirectRightAndLeft(new ClassTester(-20, 2));
            var expectedOutputRL = new KeyValuePair <ClassTester, ClassTester>(new ClassTester(-10, 1), null);

            Assert.AreEqual(outputRL.Key.compareByValue, expectedOutputRL.Key.compareByValue, "Right element is incorrect");
            Assert.AreEqual(outputRL.Key.otherProperties, expectedOutputRL.Key.otherProperties, "Right element is incorrect");
            Assert.AreEqual(outputRL.Value, expectedOutputRL.Value, "Left element is incorrect");
            Assert.AreEqual(outputRL.Value, expectedOutputRL.Value, "Left element is incorrect");

            Assert.AreEqual(expectedOutputTree.Count, tree.Count, "Tree size is incorrect!");

            for (int i = 0; i < expectedOutputTree.Count; i++)
            {
                Assert.AreEqual(expectedOutputTree[i], tree[i], "Tree Element at index " + i + " is incorrect");
            }
        }
Example #9
0
 public void initDrones(int num)
 {
     for (int i = 0; i < num; i++)
     {
         Drone newDrone = new Drone(i, parkinglot[i]);
         dronesDict.Add(i, newDrone);
         availableDronesId.Add(i);
     }
 }
Example #10
0
        public void MaximumTest()
        {
            OrderedSet <Number> s = new OrderedSet <Number>();

            s.Add(new Number(2));
            s.Add(new Number(4));
            s.Add(new Number(7));
            Assert.IsTrue(s.Maximum().Equals(new Number(7)));
        }
Example #11
0
        public void OrderedSet_Add_ReturnsFalseIfItemExists()
        {
            const string item = "foo";

            var set = new OrderedSet <string>();

            set.Add(item);

            Assert.False(set.Add(item));
        }
 public void TrimTwo()
 {
     var set = new OrderedSet<Story>();
     var story = new Story(new FrontpageItem { Title = "title", Link = "blah" }) { DisplayTime = DateTime.Now};
     var story2 = new Story(new FrontpageItem { Title = "title2", Link = "blah" }) {DisplayTime = DateTime.MinValue};
     set.Add(story);
     set.Add(story2);
     set.Trim(2);
     Assert.AreEqual(2, set.Count);
 }
 public void Trim()
 {
     var set = new OrderedSet<Story>();
     var story = new Story(new FrontpageItem { Title = "title", Link = "blah", Description = "shouldnt matter" }) { DisplayTime = DateTime.Now};
     var story2 = new Story(new FrontpageItem { Title = "title", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     set.Add(story);
     set.Add(story2);
     set.Trim(1);
     Assert.AreEqual(1, set.Count);
     Assert.AreEqual(story2, set[0]);
 }
Example #14
0
 public void OrderedSetTest()
 {
     var set = new OrderedSet<Story>();
     var story = new Story(new FrontpageItem { Title = "title", Link = "blah", Description = "shouldnt matter" });
     var story2 = new Story(new FrontpageItem { Title = "title", Link = "blah", Description = "diff but irrelevant" });
     set.Add(story);
     set.Add(story2);
     set.RemoveLast();
     Assert.AreEqual(1, set.Count);
     Assert.AreEqual(story2, set[0]);
 }
Example #15
0
        private static IEnumerable <FPoint> CreateEventList(IEnumerable <Segment> mergedSegments)
        {
            OrderedSet <FPoint> eventList = new OrderedSet <FPoint>();

            foreach (Segment segment in mergedSegments)
            {
                eventList.Add(segment.startPt);
                eventList.Add(segment.endPt);
            }
            return(eventList);
        }
Example #16
0
        public void DuplicateObjectTest()
        {
            OrderedSet<Person> actual = new OrderedSet<Person>();
            Person p1 = new Person { FirstName = "Granville", LastName = "Barnett" };
            Person p2 = new Person { FirstName = "Granville", LastName = "Barnett" };

            actual.Add(p1);
            actual.Add(p2);

            Assert.AreEqual(1, actual.Count);
        }
        public void Set(K key, V value)
        {
            if (capacity > dict.Count)
            {
                if (!dict.ContainsKey(key))
                {
                    dict.Add(key, value);
                }
                else
                {
                    dict[key] = value;

                    Pair <K, V> item = set.Where(x => x.Key.CompareTo(key) == 0).First();

                    set.Remove(item);
                }

                set.Add(new Pair <K, V>(key, value, number));

                number++;

                return;
            }

            if (dict.ContainsKey(key))
            {
                Pair <K, V> item = set.Where(x => x.Key.CompareTo(key) == 0).First();

                set.Remove(item);

                dict[key] = value;

                set.Add(new Pair <K, V>(key, value, number++));
                return;
            }

            else
            {
                var pair = set.RemoveLast();

                dict.Remove(pair.Key);

                if (!dict.ContainsKey(key))
                {
                    dict.Add(key, value);
                }
                else
                {
                    dict[key] = value;
                }
                set.Add(new Pair <K, V>(key, value, number++));
            }
        }
 public void initDrones(int num)
 {
     for (int i = 0; i < num; i++)
     {
         // Debug.Log(parkinglot[parkingInterval * i]);
         Drone newDrone = new Drone(i, parkinglot[i]);
         newDrone.EnableArrows = this.EnableArrows;
         newDrone.gameObjectPointer.GetComponent <DroneProperties>().EnableLineRender = this.EnableLineRender;
         dronesDict.Add(i, newDrone);
         availableDronesId.Add(i);
     }
 }
Example #19
0
 private void initializeEvents(OrderedSet <Event> Q)
 {
     for (int i = 0; i < segments.Count; ++i)
     {
         if (segments[i].Start.X > segments[i].End.X)
         {
             swap(segments[i].Start, segments[i].End);
         }
         Q.Add(new Event(segments[i].End, PointType.End, i, null, null));
         Q.Add(new Event(segments[i].Start, PointType.Start, i, null, null));
     }
 }
Example #20
0
        private void handleEvent(Event curEvent, OrderedSet <Event> L, OrderedSet <Event> Q, List <Point> outPoints)
        {
            switch (curEvent.pType)
            {
            case PointType.Start:
            {
                KeyValuePair <Event, Event> upLow = L.DirectUpperAndLower(curEvent);
                if (upLow.Key != null)
                {
                    checkIntersection(upLow.Key, curEvent, Q, outPoints);
                }
                if (upLow.Value != null)
                {
                    checkIntersection(curEvent, upLow.Value, Q, outPoints);
                }
                L.Add(curEvent);
                break;
            }

            case PointType.End:
            {
                KeyValuePair <Event, Event> upLow = L.DirectUpperAndLower(curEvent);
                if (upLow.Key != null && upLow.Value != null)
                {
                    checkIntersection(upLow.Key, upLow.Value, Q, outPoints);
                }
                L.Remove(new Event(segments[curEvent.segIdx].Start, PointType.Start, curEvent.segIdx, null, null));
                break;
            }

            case PointType.Intersection:
            {
                Event upup   = L.DirectUpperAndLower(curEvent.upper).Key;
                Event lowlow = L.DirectUpperAndLower(curEvent.lower).Value;
                if (upup != null)
                {
                    checkIntersection(upup, curEvent.lower, Q, outPoints);
                }
                if (lowlow != null)
                {
                    checkIntersection(curEvent.upper, lowlow, Q, outPoints);
                }
                L.Remove(curEvent.upper); L.Remove(curEvent.lower);
                curEvent.lower.point.X = curEvent.point.X; curEvent.lower.point.Y = curEvent.point.Y;
                curEvent.upper.point.X = curEvent.point.X; curEvent.upper.point.Y = curEvent.point.Y;
                L.Add(curEvent.upper); L.Add(curEvent.lower);
                break;
            }

            default:
                break;
            }
        }
Example #21
0
        public void UseCustomEquality()
        {
            //Two persons are considered the same if they have the same id number
            var set = new OrderedSet <Person>(new IdNumberComparer());

            Assert.True(set.Add(new Person()
            {
                IdNumber = 1, Name = "John Doe"
            }));
            Assert.False(set.Add(new Person()
            {
                IdNumber = 1, Name = "Richard Bauer"
            }));
        }
Example #22
0
        public void OrderedSet_OrdersItems_ByInsertionOrder()
        {
            const string firstItem  = "foo";
            const string secondItem = "bar";

            var set = new OrderedSet <string>();

            set.Add(firstItem);
            set.Add(secondItem);

            var expectedOrder = new[] { firstItem, secondItem };

            Assert.Equal(expectedOrder, set);
        }
Example #23
0
        static void Main(string[] args)
        {
            OrderedSet<int> orderedSet = new OrderedSet<int>();
            orderedSet.Add(5);
            orderedSet.Add(3);
            orderedSet.Add(7);
            orderedSet.Add(1);
            orderedSet.Add(4);
            orderedSet.Add(6);
            orderedSet.Add(8);
            orderedSet.Add(2);

            foreach (var i in orderedSet)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine($"Number of elements (should be 7): {orderedSet.Count}");
            Console.WriteLine($"Check if set contains 3 (it should): {orderedSet.Contains(3)}");
            Console.WriteLine($"Try removing 3 (should succeed): {orderedSet.Remove(3)}");
            Console.WriteLine($"Try removing 3 (should fail): {orderedSet.Remove(3)}");
            Console.WriteLine($"Try removing 5 (should succeed): {orderedSet.Remove(5)}");
            Console.WriteLine($"Check if set contains 5 (it should not): {orderedSet.Contains(5)}");
            Console.WriteLine($"Number of elements (should be 5): {orderedSet.Count}");

            foreach (var i in orderedSet)
            {
                Console.WriteLine(i);
            }
        }
Example #24
0
        public IntervalNode(List <Interval <T, D> > intervalList)
        {
            intervals = new OrderedDictionary <Interval <T, D>, List <Interval <T, D> > >();

            var endpoints = new OrderedSet <D>();

            foreach (var interval in intervalList)
            {
                endpoints.Add(interval.Start);
                endpoints.Add(interval.End);
            }

            Nullable <D> median = GetMedian(endpoints);

            center = median.GetValueOrDefault();

            List <Interval <T, D> > left  = new List <Interval <T, D> >();
            List <Interval <T, D> > right = new List <Interval <T, D> >();

            foreach (Interval <T, D> interval in intervalList)
            {
                if (interval.End.CompareTo(center) < 0)
                {
                    left.Add(interval);
                }
                else if (interval.Start.CompareTo(center) > 0)
                {
                    right.Add(interval);
                }
                else
                {
                    List <Interval <T, D> > posting;
                    if (!intervals.TryGetValue(interval, out posting))
                    {
                        posting = new List <Interval <T, D> >();
                        intervals.Add(interval, posting);
                    }
                    posting.Add(interval);
                }
            }

            if (left.Count > 0)
            {
                leftNode = new IntervalNode <T, D>(left);
            }
            if (right.Count > 0)
            {
                rightNode = new IntervalNode <T, D>(right);
            }
        }
Example #25
0
    public void initDrones(int num)
    {
        int units           = 16;
        int rowcapacity     = 5;
        int parkingInterval = units / rowcapacity;
        int rowNeeded       = num / rowcapacity;

        for (int i = 0; i < num; i++)
        {
            // Debug.Log(parkinglot[parkingInterval * i]);
            Drone newDrone = new Drone(i, parkinglot[parkingInterval * i]);
            dronesDict.Add(i, newDrone);
            availableDronesId.Add(i);
        }
    }
Example #26
0
        public void DuplicateObjectTest()
        {
            OrderedSet <Person> actual = new OrderedSet <Person>();
            Person p1 = new Person {
                FirstName = "Granville", LastName = "Barnett"
            };
            Person p2 = new Person {
                FirstName = "Granville", LastName = "Barnett"
            };

            actual.Add(p1);
            actual.Add(p2);

            Assert.AreEqual(1, actual.Count);
        }
Example #27
0
        /// Summary
        /// Time: 4 min 10 sec
        /// Pattern: AAAA, State Relation
        /// Failing Test - Exposed a NullReferenceException in Person class. This could be a minor issue as Person class is a
        ///                temporary class written for testing purposes.
        public void DuplicateObjectTest([PexAssumeUnderTest] OrderedSet <Person> actual, string firstname, string lastname)
        {
            int    prevCount = actual.Count;
            Person p1        = new Person {
                FirstName = firstname, LastName = lastname
            };
            Person p2 = new Person {
                FirstName = firstname, LastName = lastname
            };

            actual.Add(p1);
            actual.Add(p2);

            PexAssert.AreEqual(prevCount + 1, actual.Count);
        }
Example #28
0
        public void InsertionOrderIsPreserved()
        {
            var set = new OrderedSet <int>();

            Assert.True(set.Add(3));
            Assert.True(set.Add(1));
            Assert.True(set.Add(2));

            List <int> setItems = set.ToList();

            Assert.Equal(setItems.Count, 3);
            Assert.Equal(setItems[0], 3);
            Assert.Equal(setItems[1], 1);
            Assert.Equal(setItems[2], 2);
        }
Example #29
0
        public static void Calculate(Graph graph, string name)
        {
            if (!graph.VertexMap.ContainsKey(name))
            {
                throw new KeyNotFoundException("Start vertex not found");
            }

            graph.ClearAll();

            var pq        = new OrderedSet <Path>();
            var start     = graph.VertexMap[name];
            var nodesSeen = 0;

            pq.Add(new Path(start, 0));
            start.Dist = 0;

            while (pq.Count > 0 && nodesSeen < graph.VertexMap.Count)
            {
                var vrec = pq.RemoveFirst();
                var v    = vrec.Destination;

                if (v.Scratch != 0)
                {
                    continue;
                }

                v.Scratch = 1;
                nodesSeen++;

                foreach (var edge in v.Adjacent)
                {
                    var w   = edge.Destination;
                    var cvw = edge.Cost;

                    if (cvw < 0)
                    {
                        throw new Exception("Graph has negative edges");
                    }

                    if (w.Dist > v.Dist + cvw)
                    {
                        w.Dist     = v.Dist + cvw;
                        w.Previous = v;
                        pq.Add(new Path(w, w.Dist));
                    }
                }
            }
        }
Example #30
0
        protected override void ResolveEmbeddedFilesFromExternalSourceDirectives(
            SyntaxTree tree,
            SourceReferenceResolver resolver,
            OrderedSet <string> embeddedFiles,
            DiagnosticBag diagnostics)
        {
            foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives(
                         d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia))
            {
                var path = (string?)directive.File.Value;
                if (path == null)
                {
                    continue;
                }

                string?resolvedPath = resolver.ResolveReference(path, tree.FilePath);
                if (resolvedPath == null)
                {
                    diagnostics.Add(
                        MessageProvider.CreateDiagnostic(
                            (int)ErrorCode.ERR_NoSourceFile,
                            directive.File.GetLocation(),
                            path,
                            CSharpResources.CouldNotFindFile));

                    continue;
                }

                embeddedFiles.Add(resolvedPath);
            }
        }
Example #31
0
        public void OrderedSet_Supports_AddingValues()
        {
            var set = new OrderedSet <string>();

            set.Add("foo");
            Assert.Single(set);
        }
        public override bool VisitDeclaration(Declaration decl)
        {
            if (AlreadyVisited(@decl))
            {
                return(false);
            }

            if (Declarations.Contains(@decl))
            {
                return(false);
            }

            if (decl == TranslationUnit)
            {
                return(true);
            }

            if (decl is TranslationUnit)
            {
                return(false);
            }

            if (decl is Class || decl is Enumeration || decl is TypedefDecl)
            {
                Declarations.Add(decl);
            }

            // No need to continue visiting after a declaration of another
            // translation unit is encountered.
            return(decl.Namespace != null && decl.Namespace.TranslationUnit == TranslationUnit);
        }
Example #33
0
        public static void Recursive(int index, Frame[] result, int start)
        {
            if (index == result.Length)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < result.Length - 1; i++)
                {
                    sb.Append(result[i].ToString());
                    sb.Append(" | ");
                }

                sb.Append(result[result.Length - 1].ToString());

                if (!combinations.Contains(sb.ToString()))
                {
                    combinations.Add(sb.ToString());
                }
            }
            else
            {
                for (int i = start; i < frames.Length; i++)
                {
                    if (!used[i])
                    {
                        used[i]       = true;
                        result[index] = frames[i];
                        Recursive(index + 1, result, start);
                        result[index] = new Frame(frames[i].Height, frames[i].Width);
                        Recursive(index + 1, result, start);
                        used[i] = false;
                    }
                }
            }
        }
Example #34
0
 public static OrderedSet<int> Create(int[] item_i)
 {
     OrderedSet<int> orderedSet = new OrderedSet<int>();
     for (int i = 0; i < item_i.Length; i++)
         orderedSet.Add(item_i[i]);
     return orderedSet;
 }
        public void AddRoom(int roomId)
        {
            if (nodesWithRoomsById.ContainsKey(roomId))
            {
                throw new ArgumentException("Room with this id already exists!");
            }

            //int previousRoomId = roomsById.RangeFrom(0, true).GetLast();
            //LinkedListNode<Room> previousNode;
            //nodesWithRoomsById.TryGetValue(previousRoomId, out previousNode);

            var nextRoomSet = roomsById.RangeTo(roomId, false);


            Room newRoom = new Room(roomId);
            LinkedListNode <Room> roomNode = new LinkedListNode <Room>(newRoom);

            if (nextRoomSet.Count == 0)
            {
                roomsLink.AddLast(roomNode);
            }
            else
            {
                int nextRoomId = nextRoomSet.GetFirst();
                LinkedListNode <Room> nextNode;
                nodesWithRoomsById.TryGetValue(nextRoomId, out nextNode);
                roomsLink.AddBefore(nextNode, roomNode);
            }

            nodesWithRoomsById.Add(roomId, roomNode);
            roomsById.Add(roomId);

            RoomCount++;
        }
Example #36
0
        private void SetFunctionDefinition(CustomNodeDefinition def)
        {
            var id = def.FunctionId;

            loadedCustomNodes[id] = def;
            loadOrder.Add(id);
        }
        public IGeometry Union()
        {
            PointLocator locater = new PointLocator();
            // use a set to eliminate duplicates, as required for union
            var exteriorCoords = new OrderedSet <Coordinate>();

            foreach (IPoint point in PointExtracter.GetPoints(_pointGeom))
            {
                Coordinate coord = point.Coordinate;
                Location   loc   = locater.Locate(coord, _otherGeom);

                if (loc == Location.Exterior)
                {
                    exteriorCoords.Add(coord);
                }
            }

            // if no points are in exterior, return the other geom
            if (exteriorCoords.Count == 0)
            {
                return(_otherGeom);
            }

            // make a puntal geometry of appropriate size
            ICoordinateSequence coords = _geomFact.CoordinateSequenceFactory.Create(exteriorCoords.ToArray());
            IGeometry           ptComp = coords.Count == 1 ? (IGeometry)_geomFact.CreatePoint(coords.GetCoordinate(0)) : _geomFact.CreateMultiPoint(coords);

            // add point component to the other geometry
            return(GeometryCombiner.Combine(ptComp, _otherGeom));
        }
        public IGeometry Union()
        {
            PointLocator locater = new PointLocator();
            // use a set to eliminate duplicates, as required for union
            var exteriorCoords = new OrderedSet<Coordinate>();

            foreach (IPoint point in PointExtracter.GetPoints(_pointGeom))
            {
                Coordinate coord = point.Coordinate;
                Location loc = locater.Locate(coord, _otherGeom);

                if (loc == Location.Exterior)
                {
                    exteriorCoords.Add(coord);
                }
            }

            // if no points are in exterior, return the other geom
            if (exteriorCoords.Count == 0)
            {
                return _otherGeom;
            }

            // make a puntal geometry of appropriate size
            ICoordinateSequence coords = _geomFact.CoordinateSequenceFactory.Create(exteriorCoords.ToArray());
            IGeometry ptComp = coords.Count == 1 ? (IGeometry)_geomFact.CreatePoint(coords.GetCoordinate(0)) : _geomFact.CreateMultiPoint(coords);

            // add point component to the other geometry
            return GeometryCombiner.Combine(ptComp, _otherGeom);
        }
Example #39
0
        static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);

            Console.WriteLine("Set contains 12: {0}", set.Contains(12));
            Console.WriteLine("Set contains 123: {0}", set.Contains(123));
            Console.WriteLine("Number of elements: {0}",set.Count);
            Console.WriteLine("=========");
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }
            Console.WriteLine("Remove 17:");
            set.Remove(17);
            Console.WriteLine(string.Join(" -> ", set.ToList()));
            Console.WriteLine("=========");
            Console.WriteLine("Set contains 17: {0}", set.Contains(17));
            Console.WriteLine("Number of elements: {0}", set.Count);
            Console.WriteLine("=========");
        }
Example #40
0
    private static long FindMinSpanningTreeSum(Node<char> startingNode, int nodesCount)
    {
        HashSet<char> visitedNodes = new HashSet<char>();
        OrderedSet<Connection<char>> connections = new OrderedSet<Connection<char>>();
        long currentSum = 0;
        visitedNodes.Add(startingNode.Symbol);

        foreach (var connection in startingNode.Connections)
        {
            if (!visitedNodes.Contains(connection.toNode.Symbol))
            {
                connections.Add(connection);
            }
        }

        while (connections.Count > 0)
        {
            Connection<char> currentConnection = connections.GetFirst();
            connections.RemoveFirst();
            Node<char> currentNode = currentConnection.toNode;

            if (!visitedNodes.Contains(currentNode.Symbol))
            {
                currentSum += currentConnection.Distance;
            }

            visitedNodes.Add(currentNode.Symbol);
            if (visitedNodes.Count == nodesCount)
            {
                break;
            }

            foreach (var connection in currentNode.Connections)
            {
                if (!visitedNodes.Contains(connection.toNode.Symbol))
                {
                    connections.Add(connection);
                }
            }
        }

        return currentSum;
    }
Example #41
0
        public static void Main()
        {
            List<int> itemsToAdd = new List<int> { 17, 9, 9, 12, 19, 6, 25, 10, 15 };  

            var set = new OrderedSet<int>();

            Console.WriteLine("Adding elements: {0}", string.Join(", ", itemsToAdd));
            foreach (var item in itemsToAdd)
            {
                var added = set.Add(item);
                //// duplicate items shouldn't be added twice in the set like item 9
                Console.WriteLine("Item {0}\t: {1}", item, added ? "added" : "not added"); 
            }

            Console.WriteLine("{0}\nUsing IEnumerable foreach:", Separator);
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }
            
            Console.WriteLine("{0}\nCount: {1}", Separator, set.Count);
            Console.WriteLine("{0}\nMin: {1}", Separator, set.Min);
            Console.WriteLine("{0}\nMax: {1}", Separator, set.Max);
            Console.WriteLine("{0}\nContains {1}: {2}", Separator, ContainedValue, set.Contains(ContainedValue));
            Console.WriteLine("{0}\nContains {1}: {2}", Separator, NotContainedValue, set.Contains(NotContainedValue));

            Console.WriteLine("{0}\nUsing ForEach method:", Separator);
            set.ForEach(Console.WriteLine);
            
            Console.WriteLine("{0}\nEfter removing 19:", Separator);
            set.Remove(19);
            set.ForEach(Console.WriteLine);
            Console.WriteLine("Count: {0}", set.Count);

            Console.WriteLine("{0}\nEfter removing all items:", Separator);
            set.Remove(6);
            set.Remove(9);
            set.Remove(15);
            set.Remove(25);
            set.Remove(10);
            set.Remove(12);
            set.Remove(17);
            Console.WriteLine("Count: {0}", set.Count);
            set.ForEach(Console.WriteLine); // Shouldn't print items because the set is empty
        }
        public override bool VisitClassDecl(AST.Class @class)
        {
            foreach (var vfptr in @class.Layout.VFTables)
            {
                var uniqueEntries = new OrderedSet<VTableComponent>();
                foreach (var entry in vfptr.Layout.Components)
                    uniqueEntries.Add(entry);

                // The vftable does not have duplicated components.
                if (vfptr.Layout.Components.Count == uniqueEntries.Count)
                    continue;

                Driver.Diagnostics.Warning(
                    "Class '{0}' found with duplicated vftable components",
                    @class.Name);
                vfptr.Layout.Components = uniqueEntries.ToList();
            }

            return base.VisitClassDecl(@class);
        }
        public static void Main()
        {
            var testSet = new OrderedSet<int>();

            testSet.Add(7);
            testSet.Add(1);
            testSet.Add(72);
            testSet.Add(-27);
            testSet.Add(0);
            testSet.Add(15);

            Console.WriteLine(string.Join(", ", testSet));

            testSet.Remove(0);
            Console.WriteLine(string.Join(", ", testSet));
        }
 public void TrimLarger()
 {
     var set = new OrderedSet<Story>();
     var story = new Story(new FrontpageItem { Title = "title", Link = "blah", Description = "shouldnt matter" }) { DisplayTime = DateTime.Now};
     var story2 = new Story(new FrontpageItem { Title = "title2", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     var story3 = new Story(new FrontpageItem { Title = "title3", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     var story4 = new Story(new FrontpageItem { Title = "title4", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     var story5 = new Story(new FrontpageItem { Title = "title5", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     var story6 = new Story(new FrontpageItem { Title = "title6", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     var story7 = new Story(new FrontpageItem { Title = "title7", Link = "blah", Description = "diff but irrelevant" }) {DisplayTime = DateTime.MinValue};
     set.Add(story);
     set.Add(story2);
     set.Add(story3);
     set.Add(story4);
     set.Add(story5);
     set.Add(story6);
     set.Add(story7);
     set.Trim(3);
     Assert.AreEqual(3, set.Count);
 }
Example #45
0
        static void Main(string[] args)
        {
            OrderedSet<int> set = new OrderedSet<int>();

            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);

            Console.WriteLine(set.Contains(105));

            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            set.Remove(25);
            set.Remove(9);
            Console.WriteLine("\n");
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            set = new OrderedSet<int>();

            set.Add(1);
            set.Add(2);
            set.Add(3);
            set.Add(4);
            set.Add(5);
            set.Add(6);
            set.Add(7);

            Console.WriteLine();
        }
        static void Main()
        {
            var example1 = new OrderedSet<int>();
            example1.Add(17);
            example1.Add(9);
            example1.Add(12);
            example1.Add(19);
            example1.Add(6);
            example1.Add(25);
            example1.Add(8);

            example1.Remove(9);

            var example2 = new OrderedSet<int>();

            example2.Add(17);
            example2.Add(9);
            example2.Add(19);
            example2.Add(6);
            example2.Add(12);
            example2.Add(25);
            example2.Add(22);
            example2.Add(33);
            example2.Add(28);
            example2.Add(35);
            example2.Add(3);
            example2.Add(2);
            example2.Add(1);
            example2.Add(5);
            example2.Add(4);
            example2.Add(11);
            example2.Add(13);
            example2.Add(26);

            example2.Remove(9);
        }
        public static void Main()
        {
            OrderedSet<int> orderedSet = new OrderedSet<int>();
            orderedSet.Add(2);
            orderedSet.Add(-1);
            orderedSet.Add(5);
            orderedSet.Add(0);
            orderedSet.Add(555);
            orderedSet.Add(7);

            Console.WriteLine("Overall number of elements in the Ordered Set are: " + orderedSet.Count);
            Console.WriteLine("The elements of the Ordered Set are as follows:");
            orderedSet.PrintInOrder();

            Console.WriteLine("Does the Ordered Set countain node with value 7? " + orderedSet.Contains(7));
            Console.WriteLine("Is the value 2 removed from the Ordered Set? " + orderedSet.Remove(2));
            Console.WriteLine("Overall number of elements in the Ordered Set are: " + orderedSet.Count);
            Console.WriteLine("The elements of the Ordered Set are as follows:");

            foreach(var input in orderedSet)
            {
                Console.WriteLine(input);
            }
        }
        private void checkIntersection(Event upper,Event lower, OrderedSet<Event> Q,List<Point> outPoints)
        {
            Line a = new Line(upper.point,segments[upper.segIdx].End);
            Line b = new Line(lower.point,segments[lower.segIdx].End);

            if (HelperMethods.CheckTurn(new Line(a.Start, a.End), b.Start) == HelperMethods.CheckTurn(new Line(a.Start, a.End), b.End)
             || (HelperMethods.CheckTurn(new Line(b.Start, b.End), a.Start) == HelperMethods.CheckTurn(new Line(b.Start, b.End), a.End)))
                return;
            double aa, bb, cc, dd;
            Point interPoint;
            if (Math.Abs(a.Start.X - a.End.X) < Constants.Epsilon)
            {
                bb = (b.Start.Y - b.End.Y) / (b.Start.X - b.End.X);
                dd = b.Start.Y - b.Start.X * bb;
                interPoint = new Point(a.Start.X, (bb * a.Start.X + dd));
            }
            else if (Math.Abs(b.Start.X - b.End.X) < Constants.Epsilon)
            {
                aa = (a.Start.Y - a.End.Y) / (a.Start.X - a.End.X);
                cc = a.Start.Y - a.Start.X * aa;
                interPoint = new Point(b.Start.X, (aa * a.Start.X + cc));
            }
            else
            {
                aa = (a.Start.Y - a.End.Y) / (a.Start.X - a.End.X);
                bb = (b.Start.Y - b.End.Y) / (b.Start.X - b.End.X);
                cc = a.Start.Y - a.Start.X * aa;
                dd = b.Start.Y - b.Start.X * bb;
                double interX = (dd - cc) / (aa - bb);
                interPoint = new Point(interX, (aa * interX + cc));
            }
            Q.Add(new Event(interPoint, PointType.Intersection,-1 ,upper,lower));
            outPoints.Add(interPoint);
        }
        static void Main()
        {
            OrderedSet<int> set = new OrderedSet<int>();
            set.Add(20);
            set.Add(25);
            set.Add(24);
            set.Add(23);
            set.Add(22);
            set.Remove(25);
            foreach (var i in set)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine("Count : " + set.Count);
            Console.WriteLine();

            set = new OrderedSet<int>();

            set.Add(20);
            set.Add(15);
            set.Add(3);
            set.Add(4);
            set.Add(25);
            set.Add(30);
            set.Add(27);

            foreach (var element in set)
            {
                Console.WriteLine(element);
            }

            Console.WriteLine("Count : " + set.Count);

            set.Remove(25);

            Console.WriteLine();
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }

            Console.WriteLine("Count : " + set.Count);

            set.Remove(20);

            Console.WriteLine();
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }

            Console.WriteLine("Count : " + set.Count);

            set.Remove(27);

            Console.WriteLine();
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }

            Console.WriteLine("Count : " + set.Count);
        }
Example #50
0
    private static void SaveShortestPaths(Node<char> currentNode, Node<char> endNode,
        HashSet<char> visitedNodes, OrderedSet<Node<char>> nextNodes, Dictionary<char, string> paths)
    {
        if (paths.Count == 0)
        {
            paths.Add(currentNode.Symbol, currentNode.Symbol.ToString());
        }

        visitedNodes.Add(currentNode.Symbol);
        foreach (var nodeDistance in currentNode.Children)
        {
            Node<char> child = nodeDistance.Key;
            if (!visitedNodes.Contains(child.Symbol))
            {
                int temporaryWeight = nodeDistance.Value + currentNode.Weight;
                if (child.Weight == 0 || child.Weight > temporaryWeight)
                {
                    if (nextNodes.Contains(child))
                    {
                        nextNodes.Remove(child);
                    }

                    child.Weight = temporaryWeight;
                    paths[child.Symbol] = paths[currentNode.Symbol] + " -> " +
                        child.Symbol.ToString() + "(" + child.Weight + ")";
                }

                nextNodes.Add(child);
            }
        }

        Node<char> nextNode = nextNodes[0];
        nextNodes.Remove(nextNode);
        if (nextNodes.Count == 0)
        {
            return;
        }

        SaveShortestPaths(nextNode, endNode, visitedNodes, nextNodes, paths);
    }
    static void Main()
    {
        Console.Write("Bag of Integers: ");
        var bagOfInts = new Bag<int>();
        bagOfInts.Add(3);
        bagOfInts.Add(5);
        bagOfInts.Add(5);
        bagOfInts.Add(5);
        bagOfInts.Add(10);
        bagOfInts.Add(20);
        bagOfInts.Add(20);
        bagOfInts.Remove(5);
        bagOfInts.RemoveAllCopies(20);
        bagOfInts.UnionWith(new Bag<int>() { 3, 3, 4, 4, 5, 5 });
        Console.WriteLine(bagOfInts);

        Console.Write("OrderedBag of Integers: ");
        var orderedBagOfInts = new OrderedBag<int>();
        orderedBagOfInts.Add(3);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(10);
        orderedBagOfInts.Add(20);
        orderedBagOfInts.Add(20);
        orderedBagOfInts.Remove(5);
        orderedBagOfInts.RemoveAllCopies(20);
        orderedBagOfInts.UnionWith(new OrderedBag<int>() { 3, 3, 4, 4, 5, 5 });
        Console.WriteLine(orderedBagOfInts);
        Console.WriteLine("Sub-range [5...10]: " +
            orderedBagOfInts.Range(5, true, 10, true));
        
        Console.Write("Set of Integers: ");
        var setOfInts = new Set<int>();
        setOfInts.Add(3);
        setOfInts.Add(5);
        setOfInts.Add(5);
        setOfInts.Add(5);
        setOfInts.Add(10);
        setOfInts.Add(20);
        setOfInts.Add(20);
        setOfInts.Remove(5);
        setOfInts.UnionWith(new Set<int>() { 3, 4, 5 });
        Console.WriteLine(setOfInts);

        Console.Write("OrderedSet of Integers: ");
        var orderedSetOfInts = new OrderedSet<int>();
        orderedSetOfInts.Add(3);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(10);
        orderedSetOfInts.Add(20);
        orderedSetOfInts.Add(20);
        orderedSetOfInts.Remove(5);
        orderedSetOfInts.UnionWith(new OrderedSet<int>() { 3, 4, 5 });
        Console.WriteLine(orderedSetOfInts);
        Console.WriteLine("Sub-range [5...20): " +
            orderedSetOfInts.Range(5, true, 20, false));

        Console.Write("MultiDictionary<string,int>: ");
        var studentGrades = new MultiDictionary<string, int>(true);
        studentGrades.Add("Peter", 3);
        studentGrades.Add("Peter", 4);
        studentGrades.Add("Peter", 4);
        studentGrades.Add("Stanka", 6);
        studentGrades.Add("Stanka", 5);
        studentGrades.Add("Stanka", 6);
        studentGrades.Add("Tanya", 6);
        studentGrades.Add("Tanya", 4);
        Console.WriteLine(studentGrades);

        Console.WriteLine("OrderedMultiDictionary<string,int>:");
        var distancesFromSofia = new OrderedMultiDictionary<int, string>(true);
        distancesFromSofia.Add(149, "Plovdiv");
        distancesFromSofia.Add(505, "Varna");
        distancesFromSofia.Add(394, "Bourgas");
        distancesFromSofia.Add(310, "Rousse");
        distancesFromSofia.Add(163, "Pleven");
        distancesFromSofia.Add(163, "Troyan");
        foreach (var distanceTowns in distancesFromSofia)
        {
            Console.WriteLine("\t" + distanceTowns);
        }

        Console.Write("Deque<string>: ");
        var people = new Deque<string>();
        people.AddToBack("Kiro");
        people.AddToBack("Maria");
        people.AddToFront("Steve");
        people.AddManyToBack(new string[] { "Ivan", "Veronika" });
        Console.WriteLine(people);

        Console.Write("BigList<int>: ");
        var ints = new BigList<int>();
        // var ints = new List<int>();
        for (int i = 0; i < 1000000; i++)
        {
            ints.Add(i);
        }
        for (int i = 0; i < 50000; i++)
        {
            ints.Insert(i, i);
        }
        Console.WriteLine(ints.Count);
    }
Example #52
0
        protected override void ResolveEmbeddedFilesFromExternalSourceDirectives(
            SyntaxTree tree,
            SourceReferenceResolver resolver,
            OrderedSet<string> embeddedFiles,
            IList<Diagnostic> diagnostics)
        {
            foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives(
                d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia))
            {
                string path = (string)directive.File.Value;
                if (path == null)
                {
                    continue;
                }

                string resolvedPath = resolver.ResolveReference(path, tree.FilePath);
                if (resolvedPath == null)
                {
                    diagnostics.Add(
                        MessageProvider.CreateDiagnostic(
                            (int)ErrorCode.ERR_NoSourceFile,
                            directive.File.GetLocation(),
                            path,
                            CSharpResources.CouldNotFindFile));

                    continue;
                }

                embeddedFiles.Add(resolvedPath);
            }
        }
 private void initializeEvents(OrderedSet<Event> Q)
 {
     for (int i = 0; i < segments.Count; ++i)
     {
         if (segments[i].Start.X > segments[i].End.X)
             swap(segments[i].Start, segments[i].End);
         Q.Add(new Event(segments[i].End, PointType.End, i,null,null));
         Q.Add(new Event(segments[i].Start, PointType.Start, i,null,null));
     }
 }
 /// <summary>
 /// @see IJobOperator#GetRunningExecutions .
 /// </summary>
 /// <param name="jobName"></param>
 /// <returns></returns>
 /// <exception cref="NoSuchJobException">&nbsp;</exception>
 public ICollection<long?> GetRunningExecutions(string jobName)
 {
     // SLE: OrderedSet is not a ISet: must return a Collection (Interface changed for that purpose)
     ICollection<long?> set = new OrderedSet<long?>();
     foreach (JobExecution jobExecution in JobExplorer.FindRunningJobExecutions(jobName))
     {
         set.Add(jobExecution.Id);
     }
     if (!set.Any() && !JobRegistry.GetJobNames().Contains(jobName))
     {
         throw new NoSuchJobException(string.Format("No such job (either in registry or in historical data): {0}", jobName));
     }
     return set;
 }
        public static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            Console.WriteLine("Add numbers --> 19, 21, 55, 27, 66, 33, 17, 85");
            set.Add(19);
            set.Add(21);
            set.Add(55);
            set.Add(27);
            set.Add(66);
            set.Add(33);
            set.Add(17);
            set.Add(85);
            Console.WriteLine();
            Console.WriteLine("In-order print --> ");
            set.PrintInOrder(set.Root);
            Console.WriteLine();
            Console.WriteLine("Foreach --> ");
            foreach (var item in set)
            {
                Console.Write(item + " ");
            }

            Console.WriteLine();
            Console.WriteLine("EachInOrder(Action<T> action) --> ");
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Insert 44 --> ");
            set.Add(44);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Remove 66 --> ");
            set.Remove(66);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Find 17 --> ");
            var find17 = set.Find(17) != null ? "17" : "null";
            Console.WriteLine(find17);
            Console.WriteLine();
            Console.WriteLine("Find 200 --> ");
            var find200 = set.Find(200) != null ? "200" : "null";
            Console.WriteLine(find200);
            Console.WriteLine();
            Console.WriteLine("Contains 44 --> ");
            var contains44 = set.Contains(44) == true ? "true" : "false";
            Console.WriteLine(contains44);
            Console.WriteLine();
            Console.WriteLine("Contains 200 --> ");
            var contains200 = set.Contains(200) == true ? "true" : "false";
            Console.WriteLine(contains200);
            Console.WriteLine();
            Console.WriteLine("Count --> ");
            Console.WriteLine(set.Count);
            Console.WriteLine(
            "Count after Add and Remove: Add 11, Remove 55, Add 5, Add 84, Add 18, Remove 5, Remove 18 (no such value)");
            set.Add(11);
            set.Remove(55);
            set.Add(5);
            set.Add(84);
            set.Add(18);
            set.Remove(5);
            set.Remove(18);
            Console.WriteLine("Count --> {0}", set.Count);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Min value --> {0}", set.Min());
            Console.WriteLine();
            Console.WriteLine("Min value --> {0}", set.Max());
            Console.WriteLine();
            set.Clear();
            Console.WriteLine("Clear --> {0} (Count)", set.Count);
        }
Example #56
0
        public static void Main(string[] args)
        {
            var ints = new OrderedSet<int> ();

            Console.WriteLine ("Initial set:");
            ints.Add (17);
            ints.Add (17);
            ints.Add (17);
            ints.Add (9);
            ints.Add (12);
            ints.Add (19);
            ints.Add (6);
            ints.Add (25);

            foreach (var val in ints) {
                Console.WriteLine (val);
            }
            Console.WriteLine ("17 exist. {0}.", ints.Contains(17));
            Console.WriteLine ("9 exist. {0}.", ints.Contains(9));
            Console.WriteLine ("12 exist. {0}.", ints.Contains(12));
            Console.WriteLine ("18 exists. {0}.", ints.Contains(18));
            Console.WriteLine ("19 exists. {0}.", ints.Contains(19));
            Console.WriteLine ("6 exists. {0}.", ints.Contains(6));
            Console.WriteLine ("25 exists. {0}.", ints.Contains(25));
            Console.WriteLine ("27 exists. {0}.", ints.Contains(27));
            Console.WriteLine ("28 exists. {0}.", ints.Contains(28));

            Console.WriteLine ("Adding some elements:");
            ints.Add (1);
            ints.Add (2);
            ints.Add (3);
            ints.Add (4);
            ints.Add (5);
            ints.Add (7);
            ints.Add (8);
            ints.Add (10);
            foreach (var val in ints) {
                Console.WriteLine (val);
            }

            Console.WriteLine ("Removing some elements:");
            ints.Remove (2);
            ints.Remove (5);
            ints.Remove (6);
            ints.Remove (9);
            ints.Remove (17);
            ints.Remove (100);

            foreach (var val in ints) {
                Console.WriteLine (val);
            }
        }
Example #57
0
		public void SetDefaults()
		{
			DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

			StringSet = new HashedSet<string> {"foo", "bar", "baz"};

			StringDateMap = new SortedList();
			StringDateMap.Add("now", DateTime.Now);
			StringDateMap.Add("never", null); // value is persisted since NH-2199
			// according to SQL Server the big bag happened in 1753 ;)
			StringDateMap.Add("big bang", new DateTime(1753, 01, 01));
			//StringDateMap.Add( "millenium", new DateTime( 2000, 01, 01 ) );
			StringArray = StringSet.ToArray();
			StringList = new ArrayList(StringArray);
			IntArray = new int[] {1, 3, 3, 7};
			FooArray = new Foo[0];
			
			Customs = new ArrayList();
			Customs.Add(new String[] {"foo", "bar"});
			Customs.Add(new String[] {"A", "B"});
			Customs.Add(new String[] {"1", "2"});

			FooSet = new HashedSet<FooProxy>();
			Components = new FooComponent[]
				{
					new FooComponent("foo", 42, null, null),
					new FooComponent("bar", 88, null, new FooComponent("sub", 69, null, null))
				};
			TimeArray = new DateTime[]
				{
					new DateTime(),
					new DateTime(),
					new DateTime(), // H2.1 has null here, but it's illegal on .NET
					new DateTime(0)
				};

			Count = 667;
			Name = "Bazza";
			TopComponents = new ArrayList();
			TopComponents.Add(new FooComponent("foo", 11, new DateTime[] {today, new DateTime(2123, 1, 1)}, null));
			TopComponents.Add(
				new FooComponent("bar", 22, new DateTime[] {new DateTime(2007, 2, 3), new DateTime(1945, 6, 1)}, null));
			TopComponents.Add(null);
			Bag = new ArrayList();
			Bag.Add("duplicate");
			Bag.Add("duplicate");
			Bag.Add("duplicate");
			Bag.Add("unique");

			Cached = new OrderedSet<CompositeElement>();

			CompositeElement ce = new CompositeElement();
			ce.Foo = "foo";
			ce.Bar = "bar";
			CompositeElement ce2 = new CompositeElement();
			ce2.Foo = "fooxxx";
			ce2.Bar = "barxxx";
			Cached.Add(ce);
			Cached.Add(ce2);
			CachedMap = new SortedList();
			CachedMap.Add(this, ce);
		}
Example #58
0
        /// <summary>
        /// OrderedSet<T>
        /// A set based on balanced search tree (red-black) (NO DUPLICATES)
        /// Add / Find / Remove work in time O(log(N))
        /// Like .NET’s SortedSet<T>
        /// Provides fast .Range(from, to) operation
        /// </summary>
        private static void TestOrderedSet()
        {
            OrderedSet<Student> students = new OrderedSet<Student>();
            var student1 = new Student("Pesho", 21);
            var student2 = new Student("Pesho", 21);
            students.Add(student1);
            students.Add(student2);
            Console.WriteLine("Equals: " + student1.Equals(student2));
            Console.WriteLine("CompareTo: " + student1.CompareTo(student2));
            Console.WriteLine(student1.GetHashCode());
            Console.WriteLine(student2.GetHashCode());
            students.Add(student1);
            var student3 = new Student("Pesho", 22);
            var student4 = new Student("Pesho", 23);
            var student5 = new Student("Pesho", 24);
            students.Add(student3);
            students.Add(student4);
            students.Add(student5);
            foreach (var item in students)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("========== Range Age >= 22 && <= 23 ============= ");
            var rangeBag = students.Range(student3, true, student4, true);
            foreach (var item in rangeBag)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("==========ForEach(x => { x.Age += 1; Console.WriteLine(x); })============= ");
            students.ForEach(x => { x.Age += 1; Console.WriteLine(x); });
        }
 private void handleEvent(Event curEvent, OrderedSet<Event> L, OrderedSet<Event> Q, List<Point> outPoints)
 {
     switch (curEvent.pType)
     {
         case PointType.Start:
             {
                 KeyValuePair<Event, Event> upLow = L.DirectUpperAndLower(curEvent);
                 if (upLow.Key != null)
                     checkIntersection(upLow.Key, curEvent, Q, outPoints);
                 if (upLow.Value != null)
                     checkIntersection(curEvent, upLow.Value, Q, outPoints);
                 L.Add(curEvent);
                 break;
             }
         case PointType.End:
             {
                 KeyValuePair<Event, Event> upLow = L.DirectUpperAndLower(curEvent);
                 if (upLow.Key != null && upLow.Value != null)
                     checkIntersection(upLow.Key, upLow.Value, Q, outPoints);
                 L.Remove(new Event(segments[curEvent.segIdx].Start, PointType.Start, curEvent.segIdx, null, null));
                 break;
             }
         case PointType.Intersection:
             {
                 Event upup = L.DirectUpperAndLower(curEvent.upper).Key;
                 Event lowlow = L.DirectUpperAndLower(curEvent.lower).Value;
                 if (upup !=null)
                     checkIntersection(upup, curEvent.lower, Q, outPoints);
                 if (lowlow != null)
                     checkIntersection(curEvent.upper,lowlow, Q, outPoints);
                 L.Remove(curEvent.upper); L.Remove(curEvent.lower);
                 curEvent.lower.point.X = curEvent.point.X;curEvent.lower.point.Y = curEvent.point.Y;
                 curEvent.upper.point.X = curEvent.point.X; curEvent.upper.point.Y = curEvent.point.Y;
                 L.Add(curEvent.upper); L.Add(curEvent.lower);
                 break;
             }
         default:
             break;
     }
 }
        public static void Main()
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(6);
            set.Add(25);
            set.Add(4);
            set.Add(8);
            set.Add(10);
            set.Add(14);
            set.Add(18);
            set.Add(22);
            set.Add(20);
            set.Add(24);
            set.Add(28);
            set.Add(26);
            set.Add(30);
            set.Add(2);
            set.Add(1);

            Console.WriteLine(set.Contains(12));
            Console.WriteLine(set.Contains(60));

            foreach (var child in set)
            {
                Console.WriteLine(child);
            }

            // set.Remove(12);
            set.Remove(9);
        }