当前位置: 首页>>代码示例>>C#>>正文


C# SortedList.RemoveAt方法代码示例

本文整理汇总了C#中SortedList.RemoveAt方法的典型用法代码示例。如果您正苦于以下问题:C# SortedList.RemoveAt方法的具体用法?C# SortedList.RemoveAt怎么用?C# SortedList.RemoveAt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SortedList的用法示例。


在下文中一共展示了SortedList.RemoveAt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Simple

        public void Simple()
        {
            var sortedList = new SortedList<int> { 5 };

            Assert.AreEqual(sortedList.Count, 1);

            sortedList.RemoveAt(0);

            Assert.AreEqual(sortedList.Count, 0);

            sortedList.Add(5);
            sortedList.Add(2);

            Assert.AreEqual(sortedList.Count, 2);
            sortedList.RemoveAt(1);

            Assert.AreEqual(sortedList.Count, 1);

            sortedList.Add(2);

            Assert.AreEqual(sortedList.Count, 2);
            sortedList.RemoveAt(0);

            Assert.AreEqual(sortedList.Count, 1);
        }
开发者ID:havok,项目名称:ngenerics,代码行数:25,代码来源:RemoveAt.cs

示例2: ShortestPath

    public Stack ShortestPath(GameObject start, GameObject end)
    {
        InitializeNodesForShortestPath();
        start.GetComponent<NavpointScript>().SetDist(0f);

        SortedList nodes = new SortedList();

        nodes.Add (0f, start);

        while(nodes.Count > 0){
            if(end.Equals ((GameObject)nodes.GetByIndex (0))){
                break;
            }
            NavpointScript u = ((GameObject)nodes.GetByIndex (0)).GetComponent<NavpointScript>();
            nodes.RemoveAt (0);
            u.SetVisited();

            GameObject[] adj = u.GetAdjacentNodes();
            for(int i = 0; i < adj.Length; i++){
                NavpointScript v = adj[i].GetComponent<NavpointScript>();
                float alt = u.GetDistByIndex (i) + u.GetDist ();
                if(alt < v.GetDist () && !v.Visited ()){
                    v.SetDist(alt);
                    v.SetPrev(u.gameObject);
                    if(nodes.ContainsValue (v))
                        nodes.RemoveAt (nodes.IndexOfValue (v));
                    nodes.Add (alt, v.gameObject);
                }
            }
        }
        Stack s = new Stack();

        GameObject node = end;
        while(node != null){
            s.Push(node);
            node = node.GetComponent<NavpointScript>().GetPrev();
        }

        return s;
    }
开发者ID:RandomGuy928,项目名称:GD1P4_SeriousFix,代码行数:40,代码来源:NavmanagerScript.cs

示例3: Calculate

        public void Calculate(int divNum)
        {
            PrimeCalculator primeCalc = new PrimeCalculator();
            primes_ = primeCalc.GetFirstNPrimes(divNum);
            povers_ = new List<int>();
            nextMultiple_ = new SortedList<BigInt, int>();
            for (int i = 0; i < primes_.Count; i++)
            {
                povers_.Add(0);
                nextMultiple_.Add(primes_[i], i);
            }

            BigInt result = 1;

            Console.WriteLine("start");
            for (int i = 0; i < divNum; i++)
            {
                if (i%10000==0)
                    Console.WriteLine(i);
                var key = nextMultiple_.Keys[0];
                var minPrime = nextMultiple_[key];
                //result *= key;
                int pow = povers_[minPrime];
                povers_[minPrime] = (pow + 1) * 2 - 1;
                int nextPow = (povers_[minPrime] + 1) * 2 - 1;
                BigInt newValue = 1;
                for (int d = 0; d < nextPow - povers_[minPrime]; d++)
                    newValue *= primes_[minPrime];
                nextMultiple_.RemoveAt(0);
                nextMultiple_.Add(newValue, minPrime);
            }

            for (int i = 0; i < primes_.Count; i++)
            {
                if (i % 10000 == 0)
                    Console.WriteLine(i);

                BigInt primMul = 1;
                for (int j = 0; j < povers_[i]; j++)
                    primMul *= primes_[i];
                if (primMul > 1)
                {
                    result *= primMul;
                    result %= 500500507;
                }
            }
            Console.WriteLine(result % 500500507);
        }
开发者ID:balazsmolnar,项目名称:Euler,代码行数:48,代码来源:Program.cs

示例4: FindBestPathCore

        /// <summary>
        /// Gets the best possible path (approximate solution) using a A* alogrithm.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="target"></param>
        /// <param name="minSecurityLevel">The mininmum, inclusive, security level.</param>
        /// <returns></returns>
        private static PathFinder FindBestPathCore(SolarSystem start, SolarSystem target, float minSecurityLevel)
        {
            var bestDepthes = new Dictionary<SolarSystem, int>();
            var paths = new SortedList<float, PathFinder>();
            PathFinder root = new PathFinder(start);
            bestDepthes.Add(start, -1);
            paths.Add(0, root);

            while (true)
            {
                if (paths.Count == 0) return null;
                PathFinder best = null;
                int depth = 0;

                // Pick the best candidate path, but ensures it matches the best depth found so far
                while (true)
                {
                    // Picks the best one, returns if we found our target
                    best = paths.Values[0];
                    if (best.m_system == target) return best;

                    // Removes it from the list
                    paths.RemoveAt(0);

                    int bestDepth;
                    depth = best.Depth;
                    bestDepthes.TryGetValue(best.m_system, out bestDepth);
                    if (bestDepth == depth || best.m_system == start) break;
                }

                // Gets the subpaths for the best path so far.
                depth++;
                foreach (var child in best.GetChildren(depth, bestDepthes))
                {
                    // Gets the heuristic key: the shorter, the better the candidate.
                    var key = child.m_system.GetSquareDistanceWith(target) * (float)(depth * depth);
                    if (child.m_system.SecurityLevel < minSecurityLevel) key *= 100.0f;
                    while (paths.ContainsKey(key)) key++;

                    // Stores it in the sorted list.
                    paths.Add(key, child);
                }
            }

        }
开发者ID:wow4all,项目名称:evemu_server,代码行数:52,代码来源:PathFinder.cs

示例5: RUSADiffPower

        protected RUSADiffPower(List<int> avail, double napor,int countChoices)
        {
            this.countChoices = countChoices;
            availGenerators = new List<int>();

            this.napor = napor;
            availGenerators = avail;

            RUSARecords = new SortedList<int, SortedList<double, RusaRecord>>();
            for (int index=0; index < availGenerators.Count; index++) {
                RUSARecords.Add(index, new SortedList<double, RusaRecord>());
            }

            preCalc(0);
            //Logger.Info(String.Join("-", RUSARecords[0].Keys));
            for (int index=1; index < availGenerators.Count;index++ ) {
                RUSARecords.RemoveAt(RUSARecords.Count - 1);
            }
        }
开发者ID:rj128x,项目名称:VotGESInt,代码行数:19,代码来源:RUSADiffPower.cs

示例6: GetClosest

        public List<Node> GetClosest(NodeId target)
        {
            var sortedNodes = new SortedList<NodeId, Node>(Bucket.MaxCapacity);

            foreach (var b in Buckets)
            {
                foreach (var n in b.Nodes)
                {
                    var distance = n.Id.Xor(target);
                    if (sortedNodes.Count == Bucket.MaxCapacity)
                    {
                        if (distance > sortedNodes.Keys[sortedNodes.Count - 1]) //maxdistance
                            continue;
                        //remove last (with the maximum distance)
                        sortedNodes.RemoveAt(sortedNodes.Count - 1);
                    }
                    sortedNodes.Add(distance, n);
                }
            }
            return new List<Node>(sortedNodes.Values);
        }
开发者ID:haroldma,项目名称:Universal.Torrent,代码行数:21,代码来源:RoutingTable.cs

示例7: MeshNodeHunt

        /// <summary>
        /// Helper method for GetNearestFreeNodes().
        /// </summary>
        private void MeshNodeHunt(List<Polygon> sector, Vector2 blockedPoint, ref double minDistance, SortedList<double, MeshNode> nodes, PointSet<float> nodesExist)
        {
            // We accept nodes that have a distance <= minDistance+1 to the blockedPoint
            foreach (Polygon polygon in sector)
            {
                foreach (MeshNode node in polygon.GetNodes())
                {
                    double distance = HelperMethods.EuklidDistance(node.mVector, blockedPoint);
            // ReSharper disable CompareOfFloatsByEqualityOperator
                    // I make minDistance have the largest double value by simply assigning it. Simple
                    // assignment won't introduce rounding errors -> I may use exact equality test here.
                    if (minDistance == double.MaxValue || distance <= minDistance + 1)
            // ReSharper restore CompareOfFloatsByEqualityOperator
                    {
                        // Decide if we have to add or to update a node:
                        if (nodesExist.Contains(node.mVector.X, node.mVector.Y))
                        {
                            int nodeIndex = nodes.IndexOfValue(node);
                            if (distance < nodes.Keys[nodeIndex])
                                nodes.Keys[nodeIndex] = distance;
                        }
                        else
                        {
                            nodes.Add(distance, node);
                            nodesExist.Add(node.mVector.X, node.mVector.Y);
                        }

                    }

                    // Look if we can even update minDistance and throw out nodes too far away
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        while (nodes.Keys[nodes.Count-1] > minDistance + 1)
                        {
                            MeshNode nodeToDelete = nodes.Values[nodes.Count - 1];
                            nodesExist.Remove(nodeToDelete.mVector.X, nodeToDelete.mVector.Y);
                            nodes.RemoveAt(nodes.Count - 1);
                        }
                    }

                }
            }
        }
开发者ID:bethge,项目名称:GalaticChaos,代码行数:47,代码来源:PathFinder.cs

示例8: printReleventFringeSuffixes

        public void printReleventFringeSuffixes()
        {
            var fringeWordSuffixes = new SortedList<double, List<string>>(new MainControl.ReverseDoubleComparer());
            int trieIndex = 0;

            //print the fringe words suffixes to the listbox
            foreach (var trie in MainControl.MostRelevntTries)
            {
                if (isCurrentWordHasMatcher[trieIndex])
                {
                    //get list of matches
                    var tempList = trie.Matcher.GetPrefixSuggestions(MainControl.numberOfFringe, MainControl.ConsiderSuffixLength, MainControl.GetProbabilityFor,new MainControl.ReverseDoubleComparer());
                    addToMainList(fringeWordSuffixes, tempList);
                }
                trieIndex++;
            }

            //add to listbox only the words with the most highest Weight
            int i = 0;
            while (i < MainControl.numberOfFringe && fringeWordSuffixes.Count > 0)
            {
                List<string> list = fringeWordSuffixes.First().Value;
                while (list.Count > 0 && i < MainControl.numberOfFringe)
                {
                    listBox1.Items.Add(list.First());
                    list.RemoveAt(0);
                    i++;
                }
                fringeWordSuffixes.RemoveAt(0);
            }
        }
开发者ID:roeibux,项目名称:text-predict,代码行数:31,代码来源:MainWindow.cs

示例9: ReadAPP1

        /// <summary>
        /// Reads the APP1 section containing Exif metadata.
        /// </summary>
        private void ReadAPP1()
        {
            // Find the APP1 section containing Exif metadata
            app1 = file.Sections.Find(a => (a.Marker == JPEGMarker.APP1) &&
                (Encoding.ASCII.GetString(a.Header, 0, 6) == "Exif\0\0"));

            // If there is no APP1 section, add a new one after the last APP0 section (if any).
            if (app1 == null)
            {
                int insertionIndex = file.Sections.FindLastIndex(a => a.Marker == JPEGMarker.APP0);
                if (insertionIndex == -1) insertionIndex = 0;
                insertionIndex++;
                ByteOrder = BitConverterEx.ByteOrder.BigEndian;
                app1 = new JPEGSection(JPEGMarker.APP1);
                file.Sections.Insert(insertionIndex, app1);
                return;
            }
            #if DEBUG
            mMap = new MemoryBinStream();
            mMap.Seek(0, SeekOrigin.Begin);
            mMap.Write(new Bin("Exif Marker", 3, 6));
            #endif

            byte[] header = app1.Header;
            SortedList<int, IFD> ifdqueue = new SortedList<int, IFD>();
            makerNoteOffset = 0;

            // TIFF header
            int tiffoffset = 6;
            if (header[tiffoffset] == 0x49)
                ByteOrder = BitConverterEx.ByteOrder.LittleEndian;
            else
                ByteOrder = BitConverterEx.ByteOrder.BigEndian;
            BitConverterEx conv = new BitConverterEx(ByteOrder, BitConverterEx.ByteOrder.System);

            // Offset to 0th IFD
            int ifd0offset = (int)conv.ToUInt32(header, tiffoffset + 4);
            ifdqueue.Add(ifd0offset, IFD.Zeroth);

            int thumboffset = -1;
            int thumblength = 0;
            int thumbtype = -1;
            #if DEBUG
            mMap.Write(new Bin("Byte Order: " + ByteOrder.ToString(), 4, 2));
            mMap.Write(new Bin("TIFF ID: 0x00, 0x2A", 4, 2));
            mMap.Write(new Bin("Offset to 0th IFD: " + ifd0offset.ToString(), 4, 4));
            #endif
            // Read IFDs
            while (ifdqueue.Count != 0)
            {
                int ifdoffset = tiffoffset + ifdqueue.Keys[0];
                IFD currentifd = ifdqueue.Values[0];
                ifdqueue.RemoveAt(0);

                // Field count
                ushort fieldcount = conv.ToUInt16(header, ifdoffset);
            #if DEBUG
                mMap.Seek(ifdoffset, SeekOrigin.Begin);
                mMap.Write(new Bin(currentifd.ToString() + " IFD Field Count: " + fieldcount.ToString(), 5, 2));
            #endif
                for (short i = 0; i < fieldcount; i++)
                {
                    // Read field info
                    int fieldoffset = ifdoffset + 2 + 12 * i;
                    ushort tag = conv.ToUInt16(header, fieldoffset);
                    ushort type = conv.ToUInt16(header, fieldoffset + 2);
                    uint count = conv.ToUInt32(header, fieldoffset + 4);
                    byte[] value = new byte[4];
                    Array.Copy(header, fieldoffset + 8, value, 0, 4);

                    // Fields containing offsets to other IFDs
                    if (currentifd == IFD.Zeroth && tag == 0x8769)
                    {
                        int exififdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(exififdpointer, IFD.EXIF);
                    }
                    else if (currentifd == IFD.Zeroth && tag == 0x8825)
                    {
                        int gpsifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(gpsifdpointer, IFD.GPS);
                    }
                    else if (currentifd == IFD.EXIF && tag == 0xa005)
                    {
                        int interopifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(interopifdpointer, IFD.Interop);
                    }

                    // Save the offset to maker note data
                    if (currentifd == IFD.EXIF && tag == 37500)
                        makerNoteOffset = conv.ToUInt32(value, 0);

                    // Calculate the bytes we need to read
                    uint baselength = 0;
                    if (type == 1 || type == 2 || type == 7)
                        baselength = 1;
                    else if (type == 3)
                        baselength = 2;
//.........这里部分代码省略.........
开发者ID:bulutcy,项目名称:CyAutoGeoTag,代码行数:101,代码来源:ExifFile.cs

示例10: pathTo

        public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 10)
        {
            spikePrice = spikeCost;
            //int resultCost = 0;
            PathData pathData = new PathData();
            int size = board.GetLength(0);
            int[][] pointValues = new int[size][];
            for (int x = 0; x < size; x++) 
            {
               pointValues[x] = new int[size];
            }
            pointValues[currentLocation.x][currentLocation.y] = 1;
            SortedList<int, Pos> newMarkedPoints = new SortedList<int, Pos>(new DuplicateKeyComparer<int>());
            newMarkedPoints.Add(1, currentLocation);
            size--;
            while (newMarkedPoints.Count() != 0) {
                Pos pos = newMarkedPoints.First().Value;
                newMarkedPoints.RemoveAt(0);
                int basecost = pointValues[pos.x][pos.y];
                int x;
                int y;
                x = pos.x;
                y = pos.y + 1;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x + 1;
                y = pos.y;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x - 1;
                y = pos.y;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
                x = pos.x;
                y = pos.y - 1;
                if(x<= size && x >=0 && y <= size && y >=0) {
                    if (target.x == x && target.y == y) {
                        pathData.distance = tilePrice(board[x][y]) + basecost + 1;
                        break;
                    }
                    if (tilePrice(board[x][y]) != -1 && pointValues[x][y] == 0) {
                        pointValues[x][y] = tilePrice(board[x][y]) + basecost + 1;
                        newMarkedPoints.Add(pointValues[x][y], new Pos(x, y));
                    }
                }
            }
            //Console.Out.WriteLine(resultCost);

            //backtrace
            Pos currentPos = target;
            while (true) {
                //Console.Out.WriteLine(currentPos.x + "," + currentPos.y);
                int x, y, a=99999,b=99999,c=99999,d=99999;
                
                x = currentPos.x - 1;
                y = currentPos.y;
                if (x <= size && x >= 0 && y <= size && y >= 0) {
                    if (currentLocation.x == x && currentLocation.y == y) {
                        pathData.nextDirection = Direction.South;
                        break;
                    }
                    a = pointValues[x][y];

                }
                    x = currentPos.x;
                    y = currentPos.y - 1;
                if (x <= size && x >= 0 && y <= size && y >= 0) {
                    if (currentLocation.x == x && currentLocation.y == y) {
                        pathData.nextDirection = Direction.East;
                        break;
                    }
                    b = pointValues[x][y];
                }

                x = currentPos.x;
                y = currentPos.y + 1;
//.........这里部分代码省略.........
开发者ID:coveoblitz2016,项目名称:wowblitzawesome,代码行数:101,代码来源:Dijkstra.cs

示例11: ReadExifAPP1

        /// <summary>
        /// Reads the APP1 section containing Exif metadata.
        /// </summary>
        private void ReadExifAPP1()
        {
            // Find the APP1 section containing Exif metadata
            exifApp1 = Sections.Find(a => (a.Marker == JPEGMarker.APP1) &&
                a.Header.Length >= 6 &&
                (Encoding.ASCII.GetString(a.Header, 0, 6) == "Exif\0\0"));

            // If there is no APP1 section, add a new one after the last APP0 section (if any).
            if (exifApp1 == null)
            {
                int insertionIndex = Sections.FindLastIndex(a => a.Marker == JPEGMarker.APP0);
                if (insertionIndex == -1) insertionIndex = 0;
                insertionIndex++;
                exifApp1 = new JPEGSection(JPEGMarker.APP1);
                Sections.Insert(insertionIndex, exifApp1);
                if (BitConverterEx.SystemByteOrder == BitConverterEx.ByteOrder.LittleEndian)
                    ByteOrder = BitConverterEx.ByteOrder.LittleEndian;
                else
                    ByteOrder = BitConverterEx.ByteOrder.BigEndian;
                return;
            }

            byte[] header = exifApp1.Header;
            SortedList<int, IFD> ifdqueue = new SortedList<int, IFD>();
            makerNoteOffset = 0;

            // TIFF header
            int tiffoffset = 6;
            if (header[tiffoffset] == 0x49 && header[tiffoffset + 1] == 0x49)
                ByteOrder = BitConverterEx.ByteOrder.LittleEndian;
            else if (header[tiffoffset] == 0x4D && header[tiffoffset + 1] == 0x4D)
                ByteOrder = BitConverterEx.ByteOrder.BigEndian;
            else
                throw new NotValidExifFileException();

            // TIFF header may have a different byte order
            BitConverterEx.ByteOrder tiffByteOrder = ByteOrder;
            if (BitConverterEx.LittleEndian.ToUInt16(header, tiffoffset + 2) == 42)
                tiffByteOrder = BitConverterEx.ByteOrder.LittleEndian;
            else if (BitConverterEx.BigEndian.ToUInt16(header, tiffoffset + 2) == 42)
                tiffByteOrder = BitConverterEx.ByteOrder.BigEndian;
            else
                throw new NotValidExifFileException();

            // Offset to 0th IFD
            int ifd0offset = (int)BitConverterEx.ToUInt32(header, tiffoffset + 4, tiffByteOrder, BitConverterEx.SystemByteOrder);
            ifdqueue.Add(ifd0offset, IFD.Zeroth);

            BitConverterEx conv = new BitConverterEx(ByteOrder, BitConverterEx.SystemByteOrder);
            int thumboffset = -1;
            int thumblength = 0;
            int thumbtype = -1;
            // Read IFDs
            while (ifdqueue.Count != 0)
            {
                int ifdoffset = tiffoffset + ifdqueue.Keys[0];
                IFD currentifd = ifdqueue.Values[0];
                ifdqueue.RemoveAt(0);

                // Field count
                ushort fieldcount = conv.ToUInt16(header, ifdoffset);
                for (short i = 0; i < fieldcount; i++)
                {
                    // Read field info
                    int fieldoffset = ifdoffset + 2 + 12 * i;
                    ushort tag = conv.ToUInt16(header, fieldoffset);
                    ushort type = conv.ToUInt16(header, fieldoffset + 2);
                    uint count = conv.ToUInt32(header, fieldoffset + 4);
                    byte[] value = new byte[4];
                    Array.Copy(header, fieldoffset + 8, value, 0, 4);

                    // Fields containing offsets to other IFDs
                    if (currentifd == IFD.Zeroth && tag == 0x8769)
                    {
                        int exififdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(exififdpointer, IFD.EXIF);
                    }
                    else if (currentifd == IFD.Zeroth && tag == 0x8825)
                    {
                        int gpsifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(gpsifdpointer, IFD.GPS);
                    }
                    else if (currentifd == IFD.EXIF && tag == 0xa005)
                    {
                        int interopifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(interopifdpointer, IFD.Interop);
                    }

                    // Save the offset to maker note data
                    if (currentifd == IFD.EXIF && tag == 37500)
                        makerNoteOffset = conv.ToUInt32(value, 0);

                    // Calculate the bytes we need to read
                    uint baselength = 0;
                    if (type == 1 || type == 2 || type == 7)
                        baselength = 1;
                    else if (type == 3)
//.........这里部分代码省略.........
开发者ID:shelland,项目名称:imaging-library,代码行数:101,代码来源:JPEGFile.cs

示例12: GenerateVMTCode


//.........这里部分代码省略.........
                            {
                                xEmittedMethods.Add(xMethodIntf, true);
                            }
                        }

                    }
                }
                int? xBaseIndex = null;
                if (xType.BaseType == null)
                {
                    xBaseIndex = (int)aGetTypeID(xType);
                }
                else
                {
                    for (int t = 0; t < aTypesSet.Count; t++)
                    {
                        // todo: optimize check
                        var xItem = aTypesSet.Skip(t).First();
                        if (xItem.ToString() == xType.BaseType.ToString())
                        {
                            xBaseIndex = (int)aGetTypeID(xItem);
                            break;
                        }
                    }
                }
                if (xBaseIndex == null)
                {
                    throw new Exception("Base type not found!");
                }
                for (int x = xEmittedMethods.Count - 1; x >= 0; x--)
                {
                    if (!aMethodsSet.Contains(xEmittedMethods.Keys[x]))
                    {
                        xEmittedMethods.RemoveAt(x);
                    }
                }
                if (!xType.IsInterface)
                {
                    Push(aGetTypeID(xType));
                    Move("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), (int)aGetTypeID(xType));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(
                        new DataMember("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), new int[] { (int)aGetTypeID(xType) }));
                    Push((uint)xBaseIndex.Value);
                    xData = new byte[16 + (xEmittedMethods.Count * 4)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes(xEmittedMethods.Count); // embedded array
                    Array.Copy(xTemp, 0, xData, 8, 4);
                    xTemp = BitConverter.GetBytes(4); // embedded array
                    Array.Copy(xTemp, 0, xData, 12, 4);
                    string xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodIndexesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodAddressesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xData = new byte[16 + Encoding.Unicode.GetByteCount(xType.FullName + ", " + xType.Module.Assembly.GetName().FullName)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes((xType.FullName + ", " + xType.Module.Assembly.GetName().FullName).Length);
开发者ID:vogon101,项目名称:Cosmos,代码行数:67,代码来源:AppAssembler.cs

示例13: GetTilesInPath

    // Returns a List of HexTiles that defines the shortest path from start to end
    // Uses A* pathfinding algorithm
    // Algorithm adapted from the reference site
    // The returned List does not contain the starting node
    public List<HexTile> GetTilesInPath(int startX, int startY, int endX, int endY, bool ignoreObjects)
    {
        var startNode = GetHexTile(startX, startY);
        var endNode = GetHexTile(endX, endY);
        var goalReached = false;

        // If goal is not reachable, the path goes as close to the goal as possible
        var closestDistanceToGoal = DistanceBetween(startNode, endNode);
        var validNodeClosestToGoal = startNode;

        // Use SortedList as a priority queue
        // Frontier represents the nodes to be visited next,
        // ordered by low to high estimated distance to goal
        var frontier = new SortedList<float, HexTile>();
        frontier.Add(0, startNode);

        // Define dictionaries for "previous node" and "current cost" for each node
        var cameFrom = new Dictionary<HexTile, HexTile>();
        var costSoFar = new Dictionary<HexTile, float>();
        cameFrom[startNode] = startNode;
        costSoFar[startNode] = 0;

        // Loop while nodes are in the frontier
        while (frontier.Count > 0)
        {
            // Get first node in the frontier (smallest estimated distance to the goal)
            var currentNode = frontier.Values[0];
            frontier.RemoveAt(0);

            // If it's the goal, then we are done
            if (currentNode.Equals(endNode))
            {
                goalReached = true;
                break;
            }

            // Get neighbors depending on if want to ignore objects in the path
            List<HexTile> neighborsList;
            if (ignoreObjects) neighborsList = currentNode.Neighbors;
            else neighborsList = currentNode.TraversableNeighbors;

            // For each neighbor of currentNode
            foreach (var neighbor in neighborsList)
            {
                // Get cost from current node to neighbor
                var newCost = costSoFar[currentNode] + 1;

                // If neighbor already has a previous cost smaller than newCost, skip it
                if (costSoFar.ContainsKey(neighbor) && costSoFar[neighbor] <= newCost)
                    continue;

                // Update the cost for neighbor
                costSoFar[neighbor] = newCost;

                // Add to priorty queue based on cost and distance to the goal
                var distanceToGoal = DistanceBetween(neighbor, endNode);
                var priority = newCost + distanceToGoal + UnityEngine.Random.Range(0f, 0.5f);

                // Get another random value if the priority already exists.
                // This hack is necessary because I couldn't find a sorted structure
                // that supports duplicate keys in C#.
                while (frontier.ContainsKey(priority))
                {
                    priority = newCost + distanceToGoal + UnityEngine.Random.Range(0f, 0.5f);
                }

                frontier.Add(priority, neighbor);

                // Set the neighbor node to "come from" the current node
                cameFrom[neighbor] = currentNode;

                // Update validNodeClosestToGoal in case endNode is unreachable
                if (distanceToGoal < closestDistanceToGoal)
                {
                    closestDistanceToGoal = distanceToGoal;
                    validNodeClosestToGoal = neighbor;
                }
            }
        }

        var pathTiles = new List<HexTile>();
        var pathNode = endNode;

        // If goalReached flag is false, then return path to validNodeClosestToGoal instead
        if (!goalReached)
        {
            pathNode = validNodeClosestToGoal;
        }

        // Follow the nodes from endNode all the way back to startNode
        pathTiles.Add(pathNode);
        while (cameFrom[pathNode] != startNode)
        {
            pathNode = cameFrom[pathNode];
            pathTiles.Add(pathNode);
        }
//.........这里部分代码省略.........
开发者ID:CobaltBlack,项目名称:Project-Hex,代码行数:101,代码来源:CombatBoardManager.cs

示例14: Dijkstra


//.........这里部分代码省略.........
                                        else if (mode == RouteMode.Shortest)
                                        {
                                            // Very bad solution but I couldn't think of a simple better one.
                                            while (unsolved.ContainsKey(distances.Get(start.ID)))
                                            {
                                                distances.GetNode(start.ID).Content += 0.0000000001;
                                            }

                                            unsolved.Add(distances.Get(start.ID), start);
                                        }
                                    }

                                    if (prevs.GetNode(current.ID).Content != null &&
                                        vehicleUse.Get(prevs.GetNode(current.ID).Content.ID) == Vehicle.Car)
                                    {
                                        if (v == Vehicle.Foot)
                                        {
                                            forbiddenVehicles.Insert(start.ID, Vehicle.Car);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //dit zou niet voor moeten komen maar toch gebeurt het...
                if (!solved.ContainsKey(current.ID))
                    solved.Add(current.ID, current);

                if (unsolved.Count > 0)
                {
                    current = unsolved.Values[0];
                    unsolved.RemoveAt(0);
                }
                else
                {
                    current = null;
                }
            }

            if (found)
            {
                List<Node> nodes = new List<Node>();
                List<long> extras = graph.GetExtras();
                Node n = destination;

                List<long> busStartStop = new List<long>();

                do
                {
                    bool foundRoute = false;

                    if (extras.Contains(n.ID))
                    {
                        // Change straigt buslines in for the actual route.
                        foreach (Edge e in graph.GetEdgesFromNode(n.ID))
                        {
                            if (prevs.Get(n.ID) != null && e.Route != null)
                            {
                                if (n.ID == e.Start &&
                                    prevs.Get(n.ID).ID == e.End)
                                {
                                    Node[] busNodes = e.Route.Points;

                                    if (busNodes[0].ID == e.Start)
开发者ID:CPutz,项目名称:MyMap,代码行数:67,代码来源:RouteFinder.cs

示例15: findShortestPath

    public NavigationPath findShortestPath(GraphNode<StateConfig> start, GraphNode<StateConfig> goal)
    {
        SortedList open = new SortedList();
        HashSet<AStarNode> closed = new HashSet<AStarNode>();

        // Add the start node to the open list with its distance set to the distance
        // to the goal
        float startGoalDist = start.content.computeDistanceEuclidean(goal.content);
        open.Add(new AStarNode(start, null, 0, startGoalDist), startGoalDist);
        int iter = 0;
        while (open.Count != 0){
        //			foreach (DictionaryEntry item in open) {
        //				Debug.Log(item.Key);
        //			}

            // take off the front of the list, should be the node closest to the goal
            AStarNode front = open.GetKey(0) as AStarNode;
            //Debug.Log("Goal is " + goal);
            //Debug.Log("front is " + front.state);
            // Check if the front node is the goal, and return the path if it is.
            if (front.state.Equals(goal))
                return front.extractPath();

            open.RemoveAt(0);
            closed.Add(front);

            // Extract the list of neighbours from the front node
            List<GraphNode<StateConfig>> successors = front.state.neighbours;
            //Debug.Log("checking successors");
            foreach (var child in successors) {
            //	Debug.Log("Checking node " + child);
                bool inOpen = false;
                // Create new astarnode with the front node as the parent, and the pathcost
                // as the cost to the front plus the distance from the front to the child.
                // estimated cost temporarily set to zero, will be updated later if needed.
                AStarNode childNode = new AStarNode(child, front, front.pathCost + front.state.content.computeDistanceEuclidean(child.content), 0);
                AStarNode node;
            //	Debug.Log("Checking for this node in open list");
                foreach (DictionaryEntry entry in open) {
                    node = entry.Key as AStarNode;
            //		Debug.Log("Comparing " + childNode + " to " + node);
                    // Check the contents of the node and the child. If they
                    // are equal, the child is already in the open list
                    if (node.Equals(childNode)){
            //			Debug.Log("The two node states are equal");
                        // Cost of the identical node currently in the open list is
                        // larger than the cost of the current successor. We will replace
                        // the one currently in the open list with the new successor
                        if (node.pathCost > childNode.pathCost){
            //				Debug.Log("cost of node in open is larger than the one being examined, removing it");
                            open.Remove(node);
            //				Debug.Log("after removal open contains old node? " + open.ContainsKey(node));
                            // break so that we do not set inopen = true
                            break;
                        }
            //			Debug.Log("the path cost from the node already in the list is lower");
                        // The state is already in the open list and
                        // its path cost is lower than ours.
                        inOpen = true;
                        break;
                    }
                    //Debug.Log("Nodes not equal");
                }

                // Check if the node is already in the closed list
                bool inClosed = closed.Contains(childNode);
                //Debug.Log("Does the closed list contain the child node? " + inClosed);
                // If the node is not already in the closed or open lists (or perhaps
                // if it was in the open list but it had a higher path cost than the
                // current node) then add it to the open list, ordering by the estimated
                // cost to the goal.
                if (!inClosed && !inOpen){
                //	Debug.Log("Node is not in closed or open, so adding to the open list");
                    childNode.estCost = childNode.pathCost + childNode.state.content.computeDistanceEuclidean(goal.content);
                    try {
                        open.Add(childNode, childNode.estCost);
                    } catch (ArgumentException ex) {
                        // TODO: Sometimes we try to add nodes which are already in the open list. This
                        // hack works to prevent the error, and the search completes successfully,
                        // but there is a problem somewhere.
                        //Debug.Log("already in open");
                    }
                }
            }

        }

        return null;
    }
开发者ID:heuristicus,项目名称:DD2438,代码行数:89,代码来源:AStar.cs


注:本文中的SortedList.RemoveAt方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。