RemoveAt() public method

public RemoveAt ( int index ) : void
index int
return void
コード例 #1
0
ファイル: Interpolator.cs プロジェクト: timdetering/Endogine
        public double[,] CalcCachedInterpolationInfo(double a_dTime, SortedList a_sorted)
        {
            double[,] aReturn = new double[,]{{1}};

            int nIndex = 0;
            //			if (a_sorted.ContainsKey(a_dTime))
            nIndex = a_sorted.IndexOfKey(a_dTime);
            if (nIndex >= 0)
            {
                return new double[,]{{(double)a_sorted.GetByIndex(nIndex)}};
            }
            else
            {
                a_sorted.Add(a_dTime, -4711);
                nIndex = a_sorted.IndexOfKey(a_dTime);
                a_sorted.RemoveAt(nIndex);
            }

            //nIndex is meant to represent the next index after a_dTime.
            //If a_dTime is the same as a key, nIndex should be that key's index - 1

            if (nIndex <= 0)
                return new double[,]{{(double)a_sorted.GetByIndex(0)}};

            if (nIndex >= a_sorted.Count)
                return new double[,]{{(double)a_sorted.GetByIndex(a_sorted.Count-1)}};

            double dTimeAtIndexBefore = (double)a_sorted.GetKey(nIndex-1);
            double dTimeAtIndexAfter = (double)a_sorted.GetKey(nIndex);

            if (a_dTime == dTimeAtIndexAfter)
            {
                /*    if (nPos < nCnt) then nPos = nPos+1
            fTimePosBefore = a_paList.getPropAt(nPos-1)
            fTimePosAfter = a_paList.getPropAt(nPos)*/
            }

            double dVal1 = 0;
            double dVal2 = (double)a_sorted.GetValueList()[nIndex-1];
            double dVal3 = (double)a_sorted.GetValueList()[nIndex];
            double dVal4 = 0;
            //TODO: support commands in the list!
            //if (ilk(mvVal2) = #List) then mvVal2 = mvVal3
            //if (ilk(mvVal3) = #List) then mvVal3 = mvVal2

            if (nIndex == 1)
                dVal1 = dVal2;
            else
                dVal1 = (double)a_sorted.GetValueList()[nIndex-2];
            //if (ilk(mvVal1) = #List) then mvVal1 = mvVal2

            if (nIndex == a_sorted.Count-1)
                dVal4 = dVal3;
            else
                dVal4 = (double)a_sorted.GetValueList()[nIndex+1];
            //TODO if (ilk(mvVal4) = #List) then mvVal4 = mvVal3

            aReturn = new double[,] {{dVal1, 0}, {dVal2, dTimeAtIndexBefore}, {dVal3, dTimeAtIndexAfter}, {dVal4,0}};
            return aReturn;
        }
コード例 #2
0
 static public int RemoveAt(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         System.Int32 a1;
         checkType(l, 2, out a1);
         self.RemoveAt(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #3
0
ファイル: Archiver.cs プロジェクト: NicolasR/Composants
 /// <summary>
 /// Ajoute la ligne line à la section en forme clé=valeur
 /// </summary>
 /// <param name="section">Dictionnaire de la section</param>
 /// <param name="line">Ligne de l'archive en forme "clé=valeur"</param>
 protected void DoAddLineToSection( SortedList section, string line ) {
   if (section == null) return ;
   int pos = line.IndexOf( '=' ) ;
   if (pos == -1) {
     string trimmed = line.Trim() ;
     if (trimmed != "") section.Add( trimmed, null ) ;
   } else {
     string key = line.Substring( 0, pos ) ;
     string val = line.Substring( pos + 1 ) ;
     int index = section.IndexOfKey( key ) ;
     if (index != -1) section.RemoveAt( index ) ;
     section.Add( key, val ) ;
   }
 }
コード例 #4
0
ファイル: ArraysAlgo.cs プロジェクト: zhouhufeng/Algo
 // use a max heap (priority queue) of size k
 // (C# doesn't provide priority queue, use SortedList instead)
 public static int KthSmallest(int[] a, int k)
 {
     SortedList list = new SortedList();
     int m = a.Length - k + 1;
     for (int i = 0; i < m; i++)
         list.Add(a[i], null);
     for (int i = m; i < a.Length; i++)
     {
         if ((int)list.GetKey(0) < a[i])
         {
             list.RemoveAt(0);
             list.Add(a[i], null);
         }
     }
     return (int)list.GetKey(0);
 }
コード例 #5
0
ファイル: LayeredLayout.cs プロジェクト: ChrisMoreton/Test3
		/// <summary>
		/// Performs the arrangement of the diagram.
		/// </summary>
		public bool Arrange(IGraph graph,
			LayeredLayoutInfo info, LayoutProgress progress)
		{
			_graph = new Graph(graph);
			_info = info;
			_progress = progress;
			_current = 0;
			_total = 
				1 /*path finding*/ + 
				1 /*layers splitting*/ +
				1 /*dummify*/ + 
				6 /*minimize crossings*/ +
				4 /*swap pairs*/ +
				1 /*layout*/ +
				1 /*apply*/ +
				1 /*compact*/ + 
				1 /*dedumify*/;

			// Update progress
			if (_progress != null)
				_progress(_current, _total);

			// Initialize nodes
			foreach (GraphNode node in _graph.Nodes)
			{
				node.SetData(_Layer, -1);
				node.SetData(_UBaryCenter, 0.0);
				node.SetData(_DBaryCenter, 0.0);
				node.SetData(_ULinkCount, 0);
				node.SetData(_DLinkCount, 0);
				node.SetData(_UPriority, 0);
				node.SetData(_DPriority, 0);
				node.SetData(_GridPosition, 0);
				node.SetData(_Dummy, false);
			}

			// Initialize links
			foreach (GraphLink link in _graph.Links)
			{
				link.SetData(_DummificationLevel, 0);
			}

			// Determine the layer depth
			Path longestPath = PathFinder.FindLongestPath(graph, info.TimeLimit);
			if (longestPath == null)
				return true; // No objects in the graph

			// Update progress
			if (_progress != null)
				_progress(_current++, _total);

			_layers = new ArrayList();
			for (int i = 0; i < longestPath.Nodes.Count; i++)
				_layers.Add(new ArrayList());

			// Distribute nodes to their appropriate layers,
			// starting with the nodes from the longest path
			for (int i = 0; i < longestPath.Nodes.Count; i++)
			{
				// Find the corresponding node in the internal graph
				GraphNode node = null;
				foreach (GraphNode n in _graph.Nodes)
				{
					if (n.Node == longestPath.Nodes[i])
					{
						node = n;
						break;
					}
				}

				node.SetData(_Layer, i);
				(_layers[i] as ArrayList).Add(node);
			}

			foreach (INode node in longestPath.Nodes)
			{
				// Find the corresponding node in the internal graph
				GraphNode gnode = null;
				foreach (GraphNode n in _graph.Nodes)
				{
					if (n.Node == node)
					{
						gnode = n;
						break;
					}
				}

				AddChildren(gnode);
			}

			// For all layers whose nodes are > 1 / 20 of the total ->
			// drop nodes. This will ensure that there are no
			// too wide layers, thus improving visibility of the graph.
			int total = 0;
			bool found;
			foreach (ArrayList layer in _layers)
				total += layer.Count;

			int threshold = total / 10;
			if (total > 50 && _info.SplitLayers)
			{
				found = true;
				while (found)
				{
					found = false;

					foreach (ArrayList layer in _layers)
					{
						if (layer.Count > threshold)
						{
							// Find candidates for dropping.
							// Good candidate is a node which
							// when moved downwards will be closer
							// to its children
							SortedList candidates = new SortedList();
							foreach (GraphNode node in layer)
							{
								// Calculate total child depth
								int factor = 0;
								int nodeLayer = (int)node.GetData(_Layer);
								foreach (GraphLink link in node.OutLinks)
								{
									int childLayer = (int)link.Destination.GetData(_Layer);
									if (childLayer <= nodeLayer)
										factor += 1;
									else
										factor -= 1;
								}
								foreach (GraphLink link in node.InLinks)
								{
									int childLayer = (int)link.Origin.GetData(_Layer);
									if (childLayer <= nodeLayer)
										factor += 1;
									else
										factor -= 1;
								}

								if (factor > 0)
									candidates[factor] = node;
							}

							if (candidates.Keys.Count == 0)
								continue;

							found = true;

							ArrayList nextLayer = null;
							int ilayer = _layers.IndexOf(layer);
							if (ilayer == _layers.Count - 1)
							{
								nextLayer = new ArrayList();
								_layers.Add(nextLayer);
							}
							else
							{
								nextLayer = _layers[ilayer + 1] as ArrayList;
							}

							while (layer.Count > threshold)
							{
								if (candidates.Keys.Count == 0)
									break;

								GraphNode node = candidates.GetByIndex(candidates.Count - 1) as GraphNode;
								candidates.RemoveAt(candidates.Count - 1);

								nextLayer.Add(node);
								layer.Remove(node);
								node.SetData(_Layer, (int)node.GetData(_Layer) + 1);
							}
						}

						if (found)
							break;
					}
				}
			}

			// Check if there are directly related nodes on the same layer
			found = true;
			while (found)
			{
				found = false;

				int ilayer = 0;
				ArrayList nodesToDrop = new ArrayList();
				foreach (ArrayList layer in _layers)
				{
					nodesToDrop.Clear();
					foreach (GraphNode node in layer)
					{
						foreach (GraphLink link in node.OutLinks)
						{
							if ((int)link.Destination.GetData(_Layer) == ilayer)
							{
								// The node's child is on the same layer.
								// Mark it for dropping
								if (!nodesToDrop.Contains(link.Destination))
									nodesToDrop.Add(link.Destination);
								found = true;
							}
						}
					}

					// Drop nodes downwards
					if (found)
					{
						ArrayList curLayer = _layers[ilayer] as ArrayList;
						ArrayList nextLayer = null;
						if (ilayer == _layers.Count - 1)
						{
							nextLayer = new ArrayList();
							_layers.Add(nextLayer);
						}
						else
						{
							nextLayer = _layers[ilayer + 1] as ArrayList;
						}

						foreach (GraphNode node in nodesToDrop)
						{
							if (curLayer.Count > 1)
							{
								nextLayer.Add(node);
								curLayer.Remove(node);
								node.SetData(_Layer, (int)node.GetData(_Layer) + 1);
							}
						}

						break;
					}

					ilayer++;
				}
			}


			// Calculate initial grid positions
			foreach (ArrayList layer in _layers)
				for (int i = 0; i < layer.Count; i++)
					(layer[i] as GraphNode).SetData(_GridPosition, (double)i);

			// Update progress
			if (_progress != null)
				_progress(_current++, _total);

			// Add dummy nodes for all links which cross one or more
			// layers. Add one dummy node for each crossed layer
			Dummify();

			// Reduce crossings
			MinimizeCrossings();

			// Further reduce crossings through pair swap
			SwapPairs();

			// Arrange nodes
			Layout();

			// Update progress
			if (_progress != null)
				_progress(_current++, _total);

			// Compact levels
			if (_info.ArrowsCompactFactor != 1)
				Compact();

			// Update progress
			if (_progress != null)
				_progress(_current++, _total);

			Apply();

			// Update progress
			if (_progress != null)
				_progress(_current++, _total);

			// Reverse dummification
			Dedummify();

			// Update progress
			if (_progress != null)
				_progress(_total, _total);

			// Update nodes positions
			foreach (GraphNode node in _graph.Nodes)
				if (node.Node != null)
					node.Node.Bounds = node.Bounds;

			// Update arrow points
			foreach (GraphLink link in _graph.Links)
			{
				if (link.Link != null)
				{
					object points = link.GetData(_LinkPoints);
					if (points != null)
						link.Link.SetPoints(points as ArrayList);
				}
			}

			return true;
		}
コード例 #6
0
        public EPoint GetUpperPowerTextureSize(EPoint a_size)
        {
            EPoint sizeReturn = new EPoint();
            SortedList aAllowedSizes = new SortedList();
            int n = 4;
            for (int i = 0; i < 10; i++)
            {
                aAllowedSizes.Add(n,i);
                n*=2;
            }

            int nVal = a_size.X;
            for (int i = 0; i < 2; i++)
            {
                aAllowedSizes.Add(nVal, -1);
                int nIndex = aAllowedSizes.IndexOfValue(-1);
                aAllowedSizes.RemoveAt(nIndex);
                if (nIndex > aAllowedSizes.Count)
                    nIndex--;
                nVal = Convert.ToInt32(aAllowedSizes.GetKey(nIndex));
                if (i == 0)
                    sizeReturn.X = nVal;
                else
                    sizeReturn.Y = nVal;

                nVal = a_size.Y;
            }
            return sizeReturn;
        }
コード例 #7
0
        private static void removeZeroItems(ref SortedList averageValuations)
        {
            Dictionary<IInstrument, bool> instCol = new Dictionary<IInstrument, bool>();

            foreach (AverageValuation val in averageValuations.Values)
            {
                if (!instCol.ContainsKey(val.Instrument))
                    instCol.Add(val.Instrument, val.AvgMarketValue.IsNotZero);
                else if (!instCol[val.Instrument] && val.AvgMarketValue.IsNotZero)
                    instCol[val.Instrument] = true;
            }

            foreach (IInstrument key in instCol.Keys)
            {
                if (!instCol[key])
                {
                    for (int i = averageValuations.Count; i > 0; i--)
                    {
                        AverageValuation val = (AverageValuation)averageValuations.GetByIndex(i);
                        if (val.Instrument.Equals(key))
                            averageValuations.RemoveAt(i);
                    }
                }
            }
        }
コード例 #8
0
ファイル: Lighting.cs プロジェクト: reisergames/reactor-v1
        internal RLIGHT[] GetClosestActiveLights(Vector3 Position)
        {
            BoundingSphere posSphere = new BoundingSphere(Position, 1.0f);
            SortedList<float,RLIGHT> lights = new SortedList<float,RLIGHT>(32);
            Hashtable distances = new Hashtable(32);
            foreach (RLIGHT light in _LightList.Values)
            {

                float Distance = Vector3.Distance(light.Position.vector, Position);
                if (light.Enabled)
                {
                    switch (light.LightType)
                    {
                        case 0:
                            lights.Add(Distance, light);
                            break;
                        case 1:

                            if(lights.Count >= 32)
                            {
                                int i = 0;
                                foreach(float d in lights.Keys)
                                {
                                    if(lights[d].LightType != 0)
                                    {
                                        if(Distance < d)
                                        {
                                            lights.RemoveAt(i);
                                            break;
                                        }
                                    }
                                    i++;
                                }
                            }
                            BoundingSphere sphere = new BoundingSphere(light.Position.vector, light.Radius);
                            if (sphere.Intersects(posSphere))
                            {
                                lights.Add(Distance, light);
                            }
                            break;
                        case 2:
                            lights.Add(Distance, light);
                            break;
                        default:
                            break;
                    }
                }

            }
            lights.TrimExcess();
            List<RLIGHT> l = new List<RLIGHT>(lights.Values);

            return l.ToArray();
        }
コード例 #9
0
ファイル: QAPUtils.cs プロジェクト: HondaDai/metaheuristics
        // Implementation of the GRC solution's construction algorithm.
        public static int[] GRCSolution(QAPInstance instance, double rclThreshold)
        {
            int numFacilities = instance.NumberFacilities;
            int[] assigment = new int[numFacilities];
            int totalFacilities = numFacilities;
            int index = 0;
            double best = 0;
            double cost = 0;
            int facility = 0;
            // Restricted Candidate List.
            SortedList<double, int> rcl = new SortedList<double, int>();
            // Available cities.
            bool[] assigned = new bool[numFacilities];

            assigment[0] = Statistics.RandomDiscreteUniform(0, numFacilities-1);
            assigned[assigment[0]] = true;
            index++;
            numFacilities --;

            while (numFacilities > 0) {
                rcl = new SortedList<double, int>();
                for (int i = 0; i < totalFacilities; i++) {
                    if (!assigned[i]) {
                        cost = 0;
                        for (int j = 0; j < index; j++) {
                            cost += instance.Distances[j,index] * instance.Flows[assigment[j],i];
                        }
                        if(rcl.Count == 0) {
                            best = cost;
                            rcl.Add(cost, i);
                        }
                        else if( cost < best) {
                            // The new assignment is the new best;
                            best = cost;
                            for (int j = rcl.Count-1; j > 0; j--) {
                                if (rcl.Keys[j] > rclThreshold * best) {
                                    rcl.RemoveAt(j);
                                }
                                else {
                                    break;
                                }
                            }
                            rcl.Add(cost, i);
                        }
                        else if (cost < rclThreshold * best) {
                            // The new assigment is a mostly good candidate.
                            rcl.Add(cost, i);
                        }
                    }
                }
                facility = rcl.Values[Statistics.RandomDiscreteUniform(0, rcl.Count-1)];
                assigned[facility] = true;
                assigment[index] = facility;
                index++;
                numFacilities--;
            }

            return assigment;
        }
コード例 #10
0
ファイル: TSPUtils.cs プロジェクト: HondaDai/metaheuristics
        // Implementation of the GRC solution's construction algorithm.
        public static int[] GRCSolution(TSPInstance instance, double rclThreshold)
        {
            int numCities = instance.NumberCities;
            int[] path = new int[instance.NumberCities];
            int totalCities = numCities;
            int index = 0;
            double best = 0;
            double cost = 0;
            int city = 0;
            // Restricted Candidate List.
            SortedList<double, int> rcl = new SortedList<double, int>();
            // Available cities.
            bool[] visited = new bool[numCities];

            path[0] = Statistics.RandomDiscreteUniform(0, numCities-1);
            visited[path[0]] = true;
            numCities --;

            while (numCities > 0) {
                rcl = new SortedList<double, int>();
                for (int i = 0; i < totalCities; i++) {
                    if (!visited[i]) {
                        cost = instance.Costs[path[index], i];
                        if(rcl.Count == 0) {
                            best = cost;
                            rcl.Add(cost, i);
                        }
                        else if( cost < best) {
                            // The new city is the new best;
                            best = cost;
                            for (int j = rcl.Count-1; j > 0; j--) {
                                if (rcl.Keys[j] > rclThreshold * best) {
                                    rcl.RemoveAt(j);
                                }
                                else {
                                    break;
                                }
                            }
                            rcl.Add(cost, i);
                        }
                        else if (cost < rclThreshold * best) {
                            // The new city is a mostly good candidate.
                            rcl.Add(cost, i);
                        }
                    }
                }
                city = rcl.Values[Statistics.RandomDiscreteUniform(0, rcl.Count-1)];
                index++;
                visited[city] = true;
                path[index] = city;
                numCities--;
            }

            return path;
        }
コード例 #11
0
ファイル: SPPUtils.cs プロジェクト: HondaDai/metaheuristics
        // Implementation of the GRC solution's construction algorithm.
        public static int[] GRCSolution(SPPInstance instance, double rclThreshold)
        {
            int numItems = instance.NumberItems;
            int numSets = instance.NumberSubsets;
            int[] assigment = new int[numItems];
            int index = 0;
            double best = 0;
            double cost = 0;
            int setItem = 0;
            double[] setWeigths = new double[instance.NumberSubsets];
            instance.SubsetsWeight.CopyTo(setWeigths, 0);
            // Restricted Candidate List.
            SortedList<double, int> rcl = new SortedList<double, int>();

            assigment[0] = Statistics.RandomDiscreteUniform(0, numSets-1);

            index++;
            numItems --;

            while (numItems > 0) {
                rcl = new SortedList<double, int>();
                for (int i = 0; i < numSets; i++) {
                    cost = Math.Abs(setWeigths[i] - instance.ItemsWeight[index]);
                    if(rcl.Count == 0) {
                        best = cost;
                        rcl.Add(cost, i);
                    }
                    else if(cost < best) {
                        // The new assignment is the new best;
                        best = cost;
                        for (int j = rcl.Count-1; j > 0; j--) {
                            if (rcl.Keys[j] > rclThreshold * best) {
                                rcl.RemoveAt(j);
                            }
                            else {
                                break;
                            }
                        }
                        rcl.Add(cost, i);
                    }
                    else if (cost < rclThreshold * best) {
                        // The new assigment is a mostly good candidate.
                        rcl.Add(cost, i);
                    }
                }
                setItem = rcl.Values[Statistics.RandomDiscreteUniform(0, rcl.Count-1)];
                assigment[index] = setItem;
                setWeigths[setItem] -= instance.ItemsWeight[index];
                index++;
                numItems--;
            }
            return assigment;
        }
コード例 #12
0
        //, Excluder excluder)
        private List<RouteInstance> findPath(DateTime requestTime, RouteNode origin, RouteNode goal, int weight, int volume, NodeEvaluator evaluator, RouteExcluder excluder)
        {
            Delivery delivery = new Delivery();
            delivery.Origin = origin;
            delivery.Destination = goal;
            delivery.WeightInGrams = weight;
            delivery.VolumeInCm3 = volume;
            delivery.TimeOfRequest = requestTime;

            originPath = new Dictionary<RouteNode, RouteInstance>();
            nodeCost = new Dictionary<RouteNode, double>();
            closed = new HashSet<RouteNode>();
            var rc = new RouteComparer();
            fringe = new SortedList<RouteNode, double>(rc);

            fringe.Add(origin, 0);
            originPath.Add(origin, new OriginRouteInstance(requestTime));

            //if the queue is empty return null (no path)
            while (fringe.Count > 0)
            {
                //take new node off the top of the stack
                //this is guaranteed to be the best way to the node
                RouteNode curNode = fringe.Keys[0];

                if (closed.Contains(curNode))
                    continue;

                nodeCost.Add(curNode, fringe.Values[0]);
                closed.Add(curNode);
                fringe.RemoveAt(0);

                //if it's the goal node exit and return path
                if (curNode.Equals(goal))
                    return completeDelivery(curNode);

                //grab a list of all of the routes where the given node is the origin
                IEnumerable<Route> routes = routeService.GetAll(curNode);

                //take each route that hasn't been ommited and evaluate
                foreach (Route path in excluder.Omit(routes))
                {
                    RouteInstance nextInstance = evaluator.GetNextInstance(path);
                    RouteNode nextNode = path.Destination;

                    double totalCost = evaluator.GetValue(nextInstance, delivery);

                    //if the node is not in the fringe
                    //or the current value is lower than
                    //the new cost then set the new parent
                    if (!fringe.ContainsKey(nextNode))
                    {
                        originPath.Add(nextNode, nextInstance);
                        fringe.Add(nextNode, totalCost);
                    }
                    else if (fringe[nextNode] > totalCost)
                    {
                        originPath.Remove(nextNode);
                        fringe.Remove(nextNode);

                        originPath.Add(nextNode, nextInstance);
                        fringe.Add(nextNode, totalCost);
                    }
                }
            }
            return null;
        }
コード例 #13
0
ファイル: CallTreeForm.cs プロジェクト: engincancan/utilities
 /* record leaving of a function */
 void LeaveFunction(SortedList functions, int functionId)
 {
     int index = functions.IndexOfKey(functionId);
     if(index != -1)
     {
         int newValue = (int)functions.GetByIndex(index) - 1;
         if(newValue <= 0)
         {
             functions.RemoveAt(index);
         }
         else
         {
             functions.SetByIndex(index, newValue);
         }
     }
 }
コード例 #14
0
ファイル: Arrow.cs プロジェクト: ChrisMoreton/Test3
		internal void doRoute(bool force, Link orgnLink, Link destLink, bool nowCreating)
		{
			if (!force)
				if (!autoRoute) return;

			if (flowChart.DontRouteForAwhile)
				return;

			int i;

			float gridSize = flowChart.RoutingOptions.GridSize;

			PointF startPoint = points[0];
			PointF endPoint = points[points.Count - 1];

			// get a rectangle bounding both the origin and the destination
			RectangleF bounds = orgnLink.getNodeRect(true);
			bounds = Utilities.unionRects(bounds, destLink.getNodeRect(true));
			bounds = RectangleF.Union(bounds, Utilities.normalizeRect(
				RectangleF.FromLTRB(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y)));
			if (bounds.Width < gridSize * 4)
				bounds.Inflate(gridSize * 4, 0);
			if (bounds.Height < gridSize * 4)
				bounds.Inflate(0, gridSize * 4);
			bounds.Inflate(bounds.Width, bounds.Height);

			int oNearest = 0, dNearest = 0;
			routeGetEndPoints(ref startPoint, ref endPoint,
				ref oNearest, ref dNearest, orgnLink, destLink, nowCreating);

			// Get the starting and ending square
			Point ptStart = new Point((int)((startPoint.X - bounds.X) / gridSize),
				(int)((startPoint.Y - bounds.Y) / gridSize));
			Point ptEnd = new Point((int)((endPoint.X - bounds.X) / gridSize),
				(int)((endPoint.Y - bounds.Y) / gridSize));
			if (ptStart.X == ptEnd.X && ptStart.Y == ptEnd.Y)
				return;

			// init the route grid
			int gridCols = (int)(bounds.Width / gridSize);
			int gridRows = (int)(bounds.Height / gridSize);

			RoutingGrid routingGrid = flowChart.RoutingGrid;
			routingGrid.allocate(gridCols, gridRows, bounds, this);
			byte[,] grid = routingGrid.getCostGrid();
			PathNode[,] gridClosed = routingGrid.getClosedGrid();
			PathNode[,] gridOpen = routingGrid.getOpenGrid();

			bool hurry = (gridCols * gridRows > 90000) &&
				flowChart.RoutingOptions.DontOptimizeLongRoutes;
			RouteHeuristics calcRouteHeuristics = hurry ?
				RoutingOptions.DistSquare : flowChart.RoutingOptions.RouteHeuristics;

			routeFixEndRegions(grid, ref ptStart, oNearest, ref ptEnd, dNearest, gridCols, gridRows);
			grid[ptStart.X, ptStart.Y] = 0;
			grid[ptEnd.X, ptEnd.Y] = 0;

			//---------- A* algorithm initialization -----------
			SortedList open = new SortedList();
			ArrayList closed = new ArrayList();
			Stack stack = new Stack();

			PathNode temp = new PathNode(ptStart.X, ptStart.Y);
			temp.G = 0;
			temp.H = calcRouteHeuristics(ptStart, ptEnd);
			temp.F = temp.G + temp.H;
			open.Add(temp, temp);
			gridOpen[temp.X, temp.Y] = temp;

			// setup A* cost function
			int adjcCost = flowChart.RoutingOptions.LengthCost;
			int turnCost = flowChart.RoutingOptions.TurnCost;

			PathNode best = null;
			bool found = false;
			int iterations = 0;
			for ( ; ; )
			{
				iterations++;

				// Get the best node from the open list
				if (open.Count == 0) break;
				PathNode pstmp = open.GetByIndex(0) as PathNode;

				open.RemoveAt(0);
				gridOpen[pstmp.X, pstmp.Y] = null;

				closed.Add(pstmp);
				gridClosed[pstmp.X, pstmp.Y] = pstmp;

				if ((best = pstmp) == null) break;

				// If best == destination -> path found
				if (best.X == ptEnd.X && best.Y == ptEnd.Y)
				{
					found = true;
					break;
				}

				// Generate best's successors
				int x = best.X;
				int y = best.Y;

				int[,] off = new int[4, 2] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
				for (i = 0; i < 4; i++)
				{
					byte localCost = grid[x + off[i, 0], y + off[i, 1]];
					if (localCost == 255)
						continue;

					int g = best.G + adjcCost + localCost;
					bool straight = best.Parent == null ||
						(best.Parent.Y == best.Y && off[i, 1] == 0) ||
						(best.Parent.X == best.X && off[i, 0] == 0);
					if (best.Parent == null && oNearest >= 0 && (
						oNearest < 2 && off[i, 1] == 0 || oNearest >= 2 && off[i, 1] == 1))
						straight = false;
					if (!straight) g += turnCost;

					PathNode check = null;

					// if the successor is an open node, add it to the path
					check = gridOpen[x + off[i, 0], y + off[i, 1]];
					if (check != null)
					{
						best.Children[best.ChildCount++] = check;

						// and update its cost if now it is reached via a better path
						if (g < check.G)
						{
							open.Remove(check);		// keep sorted
							check.Parent = best;
							check.G = g;
							check.F = g + check.H;
							open.Add(check, check);	// keep sorted
						}
					}
					else
					{
						// if the successor is a closed node, add it to the path
						check = gridClosed[x + off[i, 0], y + off[i, 1]];
						if (check != null)
						{
							best.Children[best.ChildCount++] = check;

							// and update its cost if now it is reached via a better path
							if (g < check.G)
							{
								check.Parent = best;
								check.G = g;
								check.F = g + check.H;

								// and update its child items
								int gg = check.G;
								int cc = check.ChildCount;
								PathNode kid = null;
								for (int j = 0; j < cc; j++)
								{
									kid = check.Children[j];

									int gi = adjcCost;
									straight = check.Parent == null ||
										(check.Parent.Y == check.Y && check.Y == kid.Y) ||
										(check.Parent.X == check.X && check.X == kid.X);
									if (!straight) gi += turnCost;

									if (g + gi < kid.G)
									{
										bool wasOpen = gridOpen[kid.X, kid.Y] != null;
										if (wasOpen) open.Remove(kid);	// keep sorted

										kid.G = g + gi;
										kid.F = kid.G + kid.H;
										kid.Parent = check;
										stack.Push(kid);

										if (wasOpen) open.Add(kid, kid);
									}
								}
								PathNode parent;
								while (stack.Count > 0)
								{
									parent = stack.Pop() as PathNode;
									cc = parent.ChildCount;
									for (int j = 0; j < cc; j++)
									{
										kid = parent.Children[j];

										int gi = adjcCost;
										straight = parent.Parent == null ||
											(parent.Parent.Y == parent.Y && parent.Y == kid.Y) ||
											(parent.Parent.X == parent.X && parent.X == kid.X);
										if (!straight) gi += turnCost;

										if (parent.G + gi < kid.G)
										{
											bool wasOpen = gridOpen[kid.X, kid.Y] != null;
											if (wasOpen) open.Remove(kid);	// keep sorted

											kid.G = parent.G + gi;
											kid.F = kid.G + kid.H;
											kid.Parent = parent;
											stack.Push(kid);

											if (wasOpen) open.Add(kid, kid);
										}
									}
								}
							}
						}
						else
						{
							// haven't considered this grid square by now
							// create and initialize a path node for it 
							Point current = new Point(x + off[i, 0], y + off[i, 1]);
							PathNode newNode = new PathNode(current.X, current.Y);
							newNode.Parent = best;
							newNode.G = g;
							newNode.H = calcRouteHeuristics(current, ptEnd);
							newNode.F = newNode.G + newNode.H;

							// add it to the list of open nodes to be evaluated later
							open.Add(newNode, newNode);
							gridOpen[newNode.X, newNode.Y] = newNode;

							// add to the path
							best.Children[best.ChildCount++] = newNode;
						}
					}
				}
			}

			if (found)
			{
				PtCollection current = new PtCollection(0);

				current.Add(new Point((int)((points[points.Count - 1].X - bounds.X) / gridSize),
					(int)((points[points.Count - 1].Y - bounds.Y) / gridSize)));
				while (best != null)
				{
					current.Add(new Point(best.X, best.Y));
					best = best.Parent;
				}
				current.Add(new Point((int)((points[0].X - bounds.X) / gridSize),
					(int)((points[0].Y - bounds.Y) / gridSize)));

				// Remove all unneeded points
				Point pt1, pt2, pt3;
				for (i = 1; i < current.Count - 1;)
				{
					pt1 = current[i - 1];
					pt2 = current[i];
					pt3 = current[i + 1];

					if (pt1.X == pt2.X && pt2.X == pt3.X)
						current.RemoveAt(i);
					else if(pt1.Y == pt2.Y && pt2.Y == pt3.Y)
						current.RemoveAt(i);
					else
						i++;
				}

				// Save the first and last points of the arrow
				PointF ptFirst = points[0];
				PointF ptLast = points[points.Count - 1];

				// no perp. arrows on a single line
				if (style == ArrowStyle.Cascading && current.Count == 2 &&
					ptFirst.X != ptLast.X && ptFirst.Y != ptLast.Y)
				{
					Point orgPt = current[0];
					Point trgPt = current[current.Count-1];
					if (orgPt.X == trgPt.X || orgPt.Y == trgPt.Y)
					{
						Point insPt = new Point(
							(orgPt.X + trgPt.X) / 2, (orgPt.Y + trgPt.Y) / 2);
						current.Insert(1, insPt);
						current.Insert(1, insPt);
					}
				}

				// Re-segment the arrow
				points = new PointCollection(current.Count);
				points[0] = ptFirst;
				points[points.Count - 1] = ptLast;

				// Assign the points from the path
				i = current.Count - 1;
				i--; // Skip the first point
				while (i > 0)
				{
					Point pt = current[i];
					PointF ptDoc = new PointF(0, 0);
					ptDoc.X = bounds.X + pt.X * gridSize + gridSize / 2;
					ptDoc.Y = bounds.Y + pt.Y * gridSize + gridSize / 2;

					if (i == 1)
					{
						// Align to the last point
						if (pt.Y == current[0].Y)
							ptDoc.Y = ptLast.Y;
						else
							ptDoc.X = ptLast.X;
					}
					if (i == current.Count - 2)
					{
						// Align to the first point
						if (pt.Y == current[current.Count - 1].Y)
							ptDoc.Y = ptFirst.Y;
						else
							ptDoc.X = ptFirst.X;

						if (style == ArrowStyle.Cascading)
							cascadeStartHorizontal = (ptDoc.X != ptFirst.X);
					}

					points[current.Count - i - 1] = ptDoc;
					i--;
				}

				PointF ptf, ptf1, ptf2, ptf3;

				// If the line is perpendicular make it at least 2 segments
				if(style == ArrowStyle.Cascading && points.Count == 2)
				{
					ptf1 = points[0];
					ptf2 = points[points.Count - 1];
					ptf = ptf1;
					if (cascadeStartHorizontal)
						ptf.X = ptf2.X;
					else
						ptf.Y = ptf2.Y;
					points.Insert(1, ptf);
				}

				// If the line is straight there might be more unneeded points
				if (style == ArrowStyle.Polyline)
				{
					i = 0;
					while(i < points.Count - 2)
					{
						ptf1 = points[i];
						ptf2 = points[i + 2];

						ChartObject obj = flowChart.objectIntersectedBy(ptf1, ptf2,
							orgnLink.getNode(), destLink.getNode());
						if(obj == null)
							points.RemoveAt(i + 1);
						else
							i++;
					}
				}

				// If the line is bezier, smooth it a bit
				if (style == ArrowStyle.Bezier)
				{
					PointCollection newPoints = new PointCollection(0);
					newPoints.Add(points[0]);
					i = 0;
					while(i < points.Count - 2)
					{
						ptf1 = points[i];
						ptf2 = points[i + 1];

						newPoints.Add(ptf2);
						newPoints.Add(ptf2);
						if(i != points.Count - 3)
						{
							ptf3 = points[i + 2];
							ptf = new PointF((ptf2.X + ptf3.X) / 2, (ptf2.Y + ptf3.Y) / 2);
							newPoints.Add(ptf);
						}
						else
						{
							newPoints.Add(points[i + 2]);
						}
						i += 1;
					}

					if (newPoints.Count == 1)
					{
						newPoints = new PointCollection(4);

						ptf1 = points[0];
						ptf2 = points[points.Count - 1];
						ptf = new PointF((ptf1.X + ptf2.X) / 2, (ptf1.Y + ptf2.Y) / 2);
						newPoints[0] = ptf1;
						newPoints[1] = ptf;
						newPoints[2] = ptf;
						newPoints[3] = ptf2;
					}

					points.Clear();
					points = newPoints;
				}

				// Update SegmentCount property value
				if (style == ArrowStyle.Bezier)
					segmentCount = (short)((points.Count - 1) / 3);
				else
					segmentCount = (short)(points.Count - 1);
			}
			else
			{
				// No path found -> reset the arrow, leaving as little points as possible
				int ptsToLeave = 2;
				if (style == ArrowStyle.Cascading)
					ptsToLeave = 4;
				else if (style == ArrowStyle.Bezier)
					ptsToLeave = 4;

				if (style == ArrowStyle.Cascading)
				{
					cascadeOrientation = Orientation.Auto;
					segmentCount = 3;
				}
				else
					segmentCount = 1;

				while (points.Count > ptsToLeave)
					points.RemoveAt(1);

				if (style == ArrowStyle.Cascading && points.Count == 3)
					segmentCount = 2;

				updatePoints(points[points.Count - 1]);
			}

			updateArrowHeads();

			if (subordinateGroup != null)
			{
				subordinateGroup.onSegmentsChanged();
				subordinateGroup.updateObjects(new InteractionState(this, -1, Action.Modify));
			}

			resetCrossings();
			updateText();

			flowChart.fireArrowRoutedEvent(this);
		}
コード例 #15
0
 public override void RemoveAt(int index)
 {
     lock (host.SyncRoot) {
         host.RemoveAt(index);
     }
 }
コード例 #16
0
	public void TestRemoveAt() {
		SortedList sl1 = new SortedList(24);
		int k;
		string s=null;
		for (int i = 0; i < 50; i++) {
			s=string.Format("{0:D2}", i); 
			sl1.Add("kala "+s,i);
		}
		
		try {
			sl1.RemoveAt(-1);
			Fail("sl.RemoveAt: ArgumentOutOfRangeException not caught, when key is out of range");
		} catch (ArgumentOutOfRangeException) {}
		try {
			sl1.RemoveAt(100);
			Fail("sl.RemoveAt: ArgumentOutOfRangeException not caught, when key is out of range");
		} catch (ArgumentOutOfRangeException) {}
		k=sl1.Count;

		for (int i=0; i<20; i++) sl1.RemoveAt(9);
		
		AssertEquals("sl.RemoveAt: removing failed",sl1.Count,30);
		for (int i=0; i<9; i++)
			AssertEquals("sl.RemoveAt: removing failed(2)",sl1["kala "+string.Format("{0:D2}", i)],i);
		for (int i=9; i<29; i++)
			AssertEquals("sl.RemoveAt: removing failed(3)",sl1["kala "+string.Format("{0:D2}", i)],null);
		for (int i=29; i<50; i++)
			AssertEquals("sl.RemoveAt: removing failed(4)",sl1["kala "+string.Format("{0:D2}", i)],i);
	}
コード例 #17
0
ファイル: bg.cs プロジェクト: rlittletht/bg.incomplete
	/* U P D A T E  C A R B  L I S T */
	/*----------------------------------------------------------------------------
		%%Function: UpdateCarbList
		%%Qualified: bg._bg.UpdateCarbList
		%%Contact: rlittle

	----------------------------------------------------------------------------*/
	private int UpdateCarbList(BGE bgeCur, ref SortedList slbge)
	{
		// retire all the items at the beginning of the list
		while (slbge.Count > 0)
			{
			BGE bgeFirst = (BGE)slbge.GetByIndex(0);

			if (bgeFirst.Date.AddHours(4.0) > bgeCur.Date)
				break; // nothing left to retire

			slbge.RemoveAt(0);
			}

		// now, if bgeCur has carbs, then add it to the list
		if (bgeCur.Carbs > 0)
			slbge.Add(bgeCur.Key, bgeCur);

		int nCarbs = 0;

		for (int i = 0, iLast = slbge.Count; i < iLast; i++)
			{
			BGE bge = (BGE) slbge.GetByIndex(i);

			if (bge.Date != bgeCur.Date)
				nCarbs += bge.Carbs;
			}

		return nCarbs;
	}
コード例 #18
0
ファイル: SortedList.cs プロジェクト: shrah/coreclr
 [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
 public override void RemoveAt(int index)
 {
     lock (_root) {
         _list.RemoveAt(index);
     }
 }
コード例 #19
0
ファイル: RemoveAtTests.cs プロジェクト: johnhhm/corefx
        public void TestRemoveAtBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            SortedList sl2 = null;

            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            String s1 = null;
            String s2 = null;

            int i = 0;
            //
            // 	Constructor: Create SortedList using this as IComparer and default settings.
            //
            sl2 = new SortedList(this);

            //  Verify that the SortedList is not null.
            Assert.NotNull(sl2);

            //  Verify that the SortedList is empty.
            Assert.Equal(0, sl2.Count);

            //   Testcase: add few key-val pairs

            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

            //  Verify that the SortedList is empty.
            Assert.Equal(100, sl2.Count);

            //
            //   Testcase: test RemoveAt (int index)
            //
            for (i = 0; i < 100; i++)
            {
                sl2.RemoveAt((int)(99 - i)); // remove from the end
                Assert.Equal(sl2.Count, (100 - (i + 1)));
            }

            //
            // Boundary - Remove a invalid key index: -1
            //
            Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                    sl2.RemoveAt(-1);
                }
                );

            //
            // Boundary - Remove a invalid key index: 0
            //
            Assert.Throws<ArgumentOutOfRangeException>(() =>
               {
                   sl2.RemoveAt(0);
               }
               );

            //
            // Boundary - Int32.MaxValue key - expect argexc
            //
            Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                    sl2.RemoveAt(Int32.MaxValue);
                }
                );
        }
コード例 #20
0
ファイル: ASPManager.cs プロジェクト: ue96/ue96
        public static SortedList GetDeliveryTime(bool HasEnoughAvailableQty, DateTime OrderTime, int Top)
        {
            string sToday = DateTime.Now.ToString("yyyy-MM-dd");
            DateTime dt11 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 11:30");  //�����ֹ11:30

            if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                dt11 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 11:30");  //���������ֹ11:30
            else if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                dt11 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:01");  //���������ֹ00:01

            DateTime dt17 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59");  //�����ֹ23:59
            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                dt17 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 18:00");  //���������ֹ18:00

            DateTime dt15 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 18:00");  //���������ֹ18:00

            int iTimeSpan = 0;
            if (OrderTime.CompareTo(dt11) <= 0)  //����11:30ǰ
            {
                iTimeSpan = 1;
            }
            else if (OrderTime.CompareTo(dt17) <= 0)  //����23:59ǰ
            {
                iTimeSpan = 2;
            }
            else  //�㵽�ڶ�������
            {
                sToday = Convert.ToDateTime(sToday).AddDays(1).ToString(AppConst.DateFormat);
                iTimeSpan = 1;
            }

            string sql = "select @top * from workday where sysno >= (select sysno from workday where [date]='" + sToday + "' and timespan='" + iTimeSpan + "') order by sysno";
            sql = sql.Replace("@top", " top " + Convert.ToString(Top + 10));

            DataSet ds = SqlHelper.ExecuteDataSet(sql);
            if (!Util.HasMoreRow(ds))
                return null;

            int iRowCount = 0;
            SortedList sl = new SortedList();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (iRowCount == 0 || Util.TrimIntNull(dr["status"]) == (int)AppEnum.BiStatus.Valid)
                {
                    WorkdayInfo oInfo = new WorkdayInfo();
                    Map(oInfo, dr);
                    sl.Add(oInfo, null);

                    iRowCount++;
                    if (iRowCount == Top)
                        break;
                }
            }
            if (Util.TrimIntNull(ds.Tables[0].Rows[0]["status"]) != (int)AppEnum.BiStatus.Valid)  //����ʱ��Ϊ�ǹ���ʱ��
                sl.RemoveAt(0);
            if (!HasEnoughAvailableQty)  //�������������Ƴٰ���,
            {
                sl.RemoveAt(0);
            }
            sl.RemoveAt(0);

            if (!HasEnoughAvailableQty) //��������������µĶ�������Ҫ�����ܶ�����
            {
                if ((DateTime.Now.DayOfWeek == DayOfWeek.Saturday && DateTime.Now > dt15) || DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                {
                    WorkdayInfo tempInfo = (WorkdayInfo)sl.GetKey(0);
                    if (tempInfo.Date.DayOfWeek == DayOfWeek.Sunday)
                        sl.RemoveAt(0);

                    tempInfo = (WorkdayInfo)sl.GetKey(0);
                    if (tempInfo.Date.DayOfWeek == DayOfWeek.Sunday)
                        sl.RemoveAt(0);

                    tempInfo = (WorkdayInfo)sl.GetKey(0);
                    if (tempInfo.Date.DayOfWeek == DayOfWeek.Monday)
                        sl.RemoveAt(0);

                    tempInfo = (WorkdayInfo)sl.GetKey(0);
                    if (tempInfo.Date.DayOfWeek == DayOfWeek.Monday)
                        sl.RemoveAt(0);
                }
            }

            return sl;
        }
コード例 #21
0
ファイル: SortedListTest.cs プロジェクト: ItsVeryWindy/mono
		public void TestRemoveAt ()
		{
			SortedList sl1 = new SortedList (24);
			int k;

			for (int i = 0; i < 50; i++) {
				string s = string.Format ("{0:D2}", i);
				sl1.Add ("kala " + s, i);
			}

			try {
				sl1.RemoveAt (-1);
				Assert.Fail ("#A");
			} catch (ArgumentOutOfRangeException) {
			}

			try {
				sl1.RemoveAt (100);
				Assert.Fail ("#B");
			} catch (ArgumentOutOfRangeException) {
			}

			k = sl1.Count;

			for (int i = 0; i < 20; i++)
				sl1.RemoveAt (9);

			Assert.AreEqual (30, (double) sl1.Count, 30, "#C1");
			for (int i = 0; i < 9; i++)
				Assert.AreEqual (i, sl1 ["kala " + string.Format ("{0:D2}", i)], "#C2:" + i);
			for (int i = 9; i < 29; i++)
				Assert.IsNull (sl1 ["kala " + string.Format ("{0:D2}", i)], "#C3:" + i);
			for (int i = 29; i < 50; i++)
				Assert.AreEqual (i, sl1 ["kala " + string.Format ("{0:D2}", i)], "#C4:" + i);
		}
コード例 #22
0
ファイル: RoutingTable.cs プロジェクト: senditu/simpletorrent
        public List<Node> GetClosest(NodeId target)
        {
            SortedList<NodeId,Node> sortedNodes = new SortedList<NodeId,Node>(Bucket.MaxCapacity);

            foreach (Bucket b in this.buckets)
            {
                foreach (Node n in b.Nodes)
                {
                    NodeId 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);
        }