public void runQueue() { // Create a queue // Using Queue class System.Collections.Queue my_queue = new System.Collections.Queue(); // Adding elements in Queue // Using Enqueue() method my_queue.Enqueue("GFG"); my_queue.Enqueue("Geeks"); my_queue.Enqueue("GeeksforGeeks"); my_queue.Enqueue("geeks"); my_queue.Enqueue("Geeks123"); Console.WriteLine("Total elements present in my_queue: {0}", my_queue.Count); // Checking if the element is // present in the Queue or not if (my_queue.Contains("GeeksforGeeks") == true) { Console.WriteLine("Element available...!!"); } else { Console.WriteLine("Element not available...!!"); } // Obtain the topmost element of my_queue // Using Dequeue method Console.WriteLine("Topmost element of my_queue" + " is: {0}", my_queue.Dequeue()); Console.WriteLine("Total elements present in my_queue: {0}", my_queue.Count); // Obtain the topmost element of my_queue // Using Peek method Console.WriteLine("Topmost element of my_queue is: {0}", my_queue.Peek()); // After Dequeue method Console.WriteLine("Total elements present in my_queue: {0}", my_queue.Count); // Remove all the elements from the queue my_queue.Clear(); // After Clear method Console.WriteLine("Total elements present in my_queue: {0}", my_queue.Count); Console.ReadLine(); }
static public int Contains(IntPtr l) { try { System.Collections.Queue self = (System.Collections.Queue)checkSelf(l); System.Object a1; checkType(l, 2, out a1); var ret = self.Contains(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int Contains(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.Collections.Queue obj = (System.Collections.Queue)ToLua.CheckObject(L, 1, typeof(System.Collections.Queue)); object arg0 = ToLua.ToVarObject(L, 2); bool o = obj.Contains(arg0); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
private static void _Remove(string key) { if (ItemDictionary.ContainsKey(key)) { if (ItemDictionary[key].expiryDate.CompareTo(DateTime.Now) < 0) { Size -= ItemDictionary[key].value.Length; ItemDictionary.Remove(key); } else { if (!keyQueue.Contains(key)) { keyQueue.Enqueue(key); } } } }
static void Main(string[] args) { // implementar colas Queue miCola = new Queue(); // encolar objetos miCola.Enqueue("esta"); miCola.Enqueue("es"); miCola.Enqueue("una"); miCola.Enqueue("cola"); foreach (string cadena in miCola) Console.WriteLine(cadena); Console.WriteLine(miCola.Count); Console.WriteLine(miCola.Contains("esta")); Console.WriteLine(miCola.Dequeue()); Console.WriteLine(miCola.Dequeue()); Console.WriteLine(miCola.Count); foreach (string cadena in miCola) Console.WriteLine(cadena); Console.Read(); }
public void OnCycle() { try { var queue = new Queue(); lock (_cycleItems.SyncRoot) { while (_cycleItems.Count > 0) { var wiredItem = (IWiredItem) _cycleItems.Dequeue(); var item = wiredItem as IWiredCycler; if (item == null) continue; var wiredCycler = item; if (!wiredCycler.OnCycle()) if (!queue.Contains(item)) queue.Enqueue(item); } } _cycleItems = queue; } catch (Exception e) { Writer.Writer.HandleException(e, "WiredHandler.cs:OnCycle"); } }
// Checks download file list private IEnumerator CheckFileList (List<DownloadFileInfo> list) { List<DownloadFileInfo> tmp_list = new List<DownloadFileInfo>(list); List<string> verify_file_list = new List<string>(); List<string> remove_list = new List<string>(); Queue<int> rnd_list = new Queue<int>(); bool verify_success = true; int rnd_index = -1; DateTime cached_time = File.GetLastWriteTime(target_path_ + kCachedFileName); check_time_ = DateTime.Now; delete_file_list_.Clear(); // Randomly check list if (cached_list_.Count > 0) { int max_count = cached_list_.Count; int count = Math.Min(Math.Max(1, max_count / 10), 10); System.Random rnd = new System.Random((int)DateTime.Now.Ticks); while (rnd_list.Count < count) { rnd_index = rnd.Next(1, max_count + 1) - 1; if (!rnd_list.Contains(rnd_index)) rnd_list.Enqueue(rnd_index); } DebugUtils.DebugLog("Random check file count is {0}", rnd_list.Count); rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1; } // Checks local files int index = 0; foreach (DownloadFileInfo file in cached_list_) { DownloadFileInfo item = list.Find(i => i.path == file.path); if (item != null) { string path = target_path_ + file.path; FileInfo info = new FileInfo(path); if (!File.Exists(path) || item.size != info.Length || item.hash != file.hash) { remove_list.Add(file.path); } else { string filename = Path.GetFileName(item.path); if (filename[0] == '_' || index == rnd_index || File.GetLastWriteTime(path).Ticks > cached_time.Ticks) { if (index == rnd_index) { rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1; } verify_file_list.Add(file.path); MD5Async.Compute(ref path, ref item, delegate (string p, DownloadFileInfo f, bool is_match) { if (VerifyCallback != null) VerifyCallback(p); verify_file_list.Remove(f.path); if (is_match) { list.Remove(f); } else { remove_list.Add(f.path); verify_success = false; } }); } else { list.Remove(item); } } } else { remove_list.Add(file.path); } ++index; } while (verify_file_list.Count > 0) { yield return new WaitForSeconds(0.1f); } RemoveCachedList(remove_list); DebugUtils.Log("Random validation has {0}", (verify_success ? "succeeded" : "failed")); // Checks all local files if (!verify_success) { foreach (DownloadFileInfo file in cached_list_) { DownloadFileInfo item = tmp_list.Find(i => i.path == file.path); if (item != null) { verify_file_list.Add(file.path); string path = target_path_ + file.path; MD5Async.Compute(ref path, ref item, delegate (string p, DownloadFileInfo f, bool is_match) { if (VerifyCallback != null) VerifyCallback(p); verify_file_list.Remove(f.path); if (!is_match) { remove_list.Add(f.path); if (!list.Contains(f)) list.Add(f); } }); } } while (verify_file_list.Count > 0) { yield return new WaitForSeconds(0.1f); } RemoveCachedList(remove_list); } TimeSpan span = new TimeSpan(DateTime.Now.Ticks - check_time_.Ticks); DebugUtils.Log("File check total time - {0:F2}s", span.TotalMilliseconds / 1000f); total_download_count_ = list.Count; foreach (DownloadFileInfo item in list) { total_download_size_ += item.size; } if (total_download_count_ > 0) { state_ = State.Ready; if (ReadyCallback != null) ReadyCallback(total_download_count_, total_download_size_); } else { DeleteLocalFiles(); UpdateCachedList(); state_ = State.Completed; DebugUtils.Log("All resources are up to date."); OnFinishedCallback(DownloadResult.SUCCESS); } }
private static void TestStackQueneCollection() { Random rand = new Random(); Stopwatch sw = new Stopwatch(); Stack<int> stack = new Stack<int>(); Queue<int> queue = new Queue<int>(); int el; //Stack sw.Reset(); Console.Write("Adding to Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { stack.Push(i); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Search in Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { var index = stack.Contains(50000); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Removing from Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { el = stack.Pop(); el++; } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks\n"); sw.Reset(); //Queue Console.Write("Add to Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { queue.Enqueue(i); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Search in Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { queue.Contains(50000); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Removing from Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { el = queue.Dequeue(); el++; } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks\n"); }
static void Main(string[] args) { byte right = 0; byte left = 1; byte down = 2; byte up = 3; //Environment.TickCount tova 6te broi vremeto ot kakto e pusnata programata //DateTime.Now int lastFoodTime = 0; int foodDisappearTime = 8000; // 8 sec delay lastFoodTime = Environment.TickCount; Position[] directions = new Position[]{ new Position(0,1), //right new Position(0,-1),//left new Position(1,0), // down new Position(-1,0), // up }; int sleepTime = 100; int direction = right; // 0 teku6tat posoka // saotvetno kat elementi na masiva positoin Random randomNumberGenerator = new Random(); Console.BufferHeight = Console.WindowHeight; // consolata da nqma scrollbar i buffera da bude golqm kolkoto consolata Position food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), // slaga qbalkata na random mesto randomNumberGenerator.Next(0, Console.WindowWidth)); // tuka 6te ni se generira slu4aino 4islo koeto 6te opredelq kade e qbalkata Queue<Position> snakeElements = new Queue<Position>(); // tova 6te e opa6kata TUKA SE PRAVQT ZMIQTA Position position1 = new Position(); for (int i = 0; i <= 5; i++) { snakeElements.Enqueue(new Position(0, i)); } foreach (Position position in snakeElements) // obxojda vsi4kite elementi i postavqme kursora tam kadeto se namira zmiqta { Console.SetCursorPosition(position.col, position.row); // tazi poziciq priema left top kolona Console.WriteLine('*'); } while (true) { if (Console.KeyAvailable) // proverqva dali potrebitelq e natisnal nqkakvo kop4e { ConsoleKeyInfo userInput = Console.ReadKey(); // pro4ita ne6to tam if (userInput.Key == ConsoleKey.LeftArrow) { if (direction != right) // ako posokata ne e nadqsno 4ak togava da se mesti nalqvo { direction = left; } } if (userInput.Key == ConsoleKey.RightArrow) { if (direction != left) { direction = right; } } if (userInput.Key == ConsoleKey.UpArrow) { if (direction != down) { direction = up; } } if (userInput.Key == ConsoleKey.DownArrow) { if (direction != up) // ako posokata ne e nagore 4ak togava da se mestim nadolo { direction = down; } } } Position snakeHead = snakeElements.Last(); // tozi method vru6ta posledniq element ot opa6kata Position nextDirection = directions[direction]; // s tozi red vzimame na kade da se dviji zmiqta kato directions e masiva a direction 0,1,2,3 //novata poziciq na zmiqta Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);// purvo e X posle e Y kato za primer vzimame stariq direction na row i go //Position newHead = snakeElements.Last();// tova ni vru6ta glavata na na6ta zmiq i q zapisva v promenlivata new head snakeElements.Enqueue(snakeNewHead); // tozi kod slaga nova glava vseki put na novata poziciq // tova proverqva dali glavata na zmiqta ne e izlezla ot ekrana bukvalno if (snakeNewHead.row < 0 || snakeNewHead.col < 0 || snakeNewHead.row >= Console.WindowHeight || snakeNewHead.col >= Console.WindowWidth) // row = red { Console.SetCursorPosition(0, 0); Console.WriteLine(); Console.WriteLine("Game over"); Console.WriteLine("Your points are: {0}", (snakeElements.Count - 6) * 100); // tova vru6ta broq elementi na zmiqta return; // prikliu4va izpulnenieto na teku6tiq method } //TOVA E KODA AKO ZMIQTA APNE QBALKATA if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) // tuka slagame statement koito proverqva dali glavata na zmiqta se zasi4a s tazi na xranata { do { food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), // slaga qbalkata na random mesto, no tozi put prosto vzima novi stoinosti za novata qbalka randomNumberGenerator.Next(0, Console.WindowWidth)); // tuka 6te ni se generira slu4aino 4islo koeto 6te opredelq kade e qbalkata } while (snakeElements.Contains(food)); sleepTime -= 5; // da stava s 20 milisekundi po-burza Random r = new Random(); Console.Beep(r.Next(100, 10000), r.Next(60, 500)); } else // samo kogato zmiqta ne udrq lqbalkata 6te se maxa edna zvezda ot opajkata { snakeElements.Dequeue(); } // garanciqta 4e 6te imame nova qbalka i zmiq e 4e console clear e predi tqx a ne sled tqx Console.Clear(); // 4isti konzolata foreach (Position position in snakeElements) // obxojda vsi4kite elementi i postavqme kursora tam kadeto se namira zmiqta { Console.SetCursorPosition(position.col, position.row); // tazi poziciq priema left top kolona Console.WriteLine('*'); } lastFoodTime = Environment.TickCount; // broq na milisekundi ot na4aloto na sistemata // TUka e koda za kazvane na programata da 4aka 8 secundi if (Environment.TickCount - lastFoodTime >= foodDisappearTime) { Console.SetCursorPosition(food.col, food.row); // TAKA MAXAME STARATA QBALKA Console.WriteLine(" "); do { food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), // slaga qbalkata na random mesto, no tozi put prosto vzima novi stoinosti za novata qbalka randomNumberGenerator.Next(0, Console.WindowWidth)); // tuka 6te ni se generira slu4aino 4islo koeto 6te opredelq kade e qbalkata } while (snakeElements.Contains(food)); } Console.SetCursorPosition(food.col, food.row); // S TOZI KOD RISUVAME QBALKATA NA RANDOM MESTO V KONZOLATA Console.Write('@'); Thread.Sleep(sleepTime); // konzolata spira prosto bavi zmiqta s opredeleno vreme } }
static void Main() { #region InitializeConsoleWindowSize Console.SetWindowSize(Window_Width, Window_Height); Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth; #endregion #region InitializeGameElements int initialRowOfSnake = Window_Height / 2; int initialColoumOfSnake = Window_Width / 2; Direction currentDirection = initialDirection; int curentSnakeSpeed = initialSnakeSpeed; Queue<Position> snake = new Queue<Position>(); for (int i = 0; i < initialSnakeLength; i++) { snake.Enqueue(new Position(initialColoumOfSnake + i, initialRowOfSnake)); } Position snakeFood = GenerateFood(); DrawSingleElement(snakeFood, foodSymbol); DrawBorderElement(); Position snakeHead; Position snakeTail; Position headingOfSnake; Position newSnakeHead; #endregion #region Directions Position[] directions = new Position[] { new Position(-1, -1), //NorthWest new Position(0, -1), // North new Position(1, -1), //NorthtEast new Position(-1, 0), //West new Position(1, 0), //East new Position(-1, 1), //SouthWest new Position(0, 1), //South new Position(1, 1) //SouthEast }; #endregion while (true) { if (Console.KeyAvailable) { currentDirection = ReadKeyFromKeyboard(currentDirection); DrawSingleElement(new Position(1 + curentLevel.Length, 1), spaceSymbol); } snakeHead = snake.Last(); headingOfSnake = directions[(int)currentDirection]; newSnakeHead = new Position( snakeHead.Column + headingOfSnake.Column, snakeHead.Row + headingOfSnake.Row ); #region GameOverLogic if (newSnakeHead.Column < 1 || newSnakeHead.Row < 1 || newSnakeHead.Column >= Console.WindowWidth - 1 || newSnakeHead.Row >= Console.WindowHeight - 1 || snake.Contains(newSnakeHead)) { Console.Clear(); DrawSingleElement(new Position(initialColoumOfSnake - 3, initialRowOfSnake - 3), "Game Over!"); DrawSingleElement(new Position(initialColoumOfSnake - 5, initialRowOfSnake - 1), String.Format("Level reached: {0}", gameLevel)); DrawSingleElement(new Position(initialColoumOfSnake - 7, initialRowOfSnake), "(Press Esc to exit)"); ConsoleKeyInfo exitKey = Console.ReadKey(); while (exitKey.Key != ConsoleKey.Escape) { exitKey = Console.ReadKey(); } return; } #endregion #region SnakeGrowingLogic if (newSnakeHead == snakeFood) { snakeFood = GenerateFood(); DrawSingleElement(snakeFood, foodSymbol); if (curentSnakeSpeed > maxSnakeSpeed) { curentSnakeSpeed -= speedFactor; gameLevel++; } } else { snakeTail = snake.Dequeue(); DrawSingleElement(snakeTail, spaceSymbol); } snake.Enqueue(newSnakeHead); #endregion DrawSnakeElement(snake); curentLevel = String.Format("Level:{0}", gameLevel); DrawSingleElement(new Position(1, 1), curentLevel); Thread.Sleep(curentSnakeSpeed); } }
public void DikkstraImpl(GraphImpl g, int start_vertex, int dest_vertex) { Queue<int> visited_vertices = new Queue<int>(g.GetTotalNodes()); int[] distance_list = new Int32[g.GetTotalNodes()]; List<int> current_list = new List<int>(g.GetTotalNodes()); int[] shortest_vertices = new Int32[g.GetTotalNodes()]; for (int z = 0; z < g.GetTotalNodes(); z++) { distance_list[z] = Int32.MaxValue; } distance_list[start_vertex] = 0; current_list.Add(start_vertex); Node start_node = g.searchNode(start_vertex); while (current_list.Count != 0) { List<int> pseudo_priority_list = new List<int>(current_list.Count); foreach (int value in current_list) { int xxx = distance_list[value]; pseudo_priority_list.Add(xxx); } int small = pseudo_priority_list.Min(); int index = pseudo_priority_list.IndexOf(small); int current_vertex = current_list[index]; Node current_node = g.searchNode(current_vertex); List<Edge> edge_list = new List<Edge>(); edge_list = current_node.GetEdgeList(); for (int z = 0; z < edge_list.Count; z++) { int r = edge_list[z]._dest.node_id; if (!visited_vertices.Contains(r) && !current_list.Contains(r)) { current_list.Add(r); } int edge1 = g.Edge_cost(start_node, current_vertex); if (edge1 == -1) { edge1 = distance_list[current_vertex]; } if (edge1 > distance_list[current_vertex]) { edge1 = distance_list[current_vertex]; } int edge2 = g.Edge_cost(current_node, r); if (distance_list[r] > (edge1 + edge2)) { shortest_vertices[r] = r; shortest_vertices[r] = current_vertex; distance_list[r] = edge1 + edge2; } } visited_vertices.Enqueue(current_vertex); current_list.Remove(current_vertex); } for (int z = 0; z < g.GetTotalNodes(); z++) { Console.WriteLine("shortest cost to reach " + z + " from " + start_vertex + " -> " + distance_list[z]); } ReturnCostForSpecificPath(g, start_vertex, dest_vertex, distance_list, shortest_vertices); }
internal static void SetConfigValue(string key, int itemmax) { XmlDocument xmlDoc = new XmlDocument( ); xmlDoc.Load(Application.ExecutablePath + ".config"); //最多可以保存9个 Queue qu = new Queue(itemmax); foreach (XmlElement xe in xmlDoc.SelectNodes("/configuration/mathWord")) { qu.Enqueue(xe.InnerText); } if (qu.Count > 9) { qu.Dequeue( ); qu.TrimToSize( ); } //去除重复的. if (!qu.Contains(key)) qu.Enqueue(key); XmlNode root = xmlDoc.SelectSingleNode("configuration"); //主要是了保证不重复 root.RemoveAll( ); foreach (string str in qu) { XmlElement xElem = xmlDoc.CreateElement("mathWord"); xElem.InnerText = str; root.AppendChild(xElem); } xmlDoc.Save(Application.ExecutablePath + ".config"); }
public void OnCycle() { try { Queue queue = new Queue(); lock (_cycleItems.SyncRoot) { while (_cycleItems.Count > 0) { IWiredItem wiredItem = (IWiredItem) _cycleItems.Dequeue(); IWiredCycler item = wiredItem as IWiredCycler; if (item == null) continue; IWiredCycler wiredCycler = item; if (!wiredCycler.OnCycle()) if (!queue.Contains(item)) queue.Enqueue(item); } } _cycleItems = queue; } catch (Exception e) { ServerLogManager.LogException(e, MethodBase.GetCurrentMethod()); } }
private static void GetAllDependResources(string path, Queue<string> dependList) { if (!IsInit) return; var paths = AssetBundleManifestObject.GetAllDependencies(path.ToLower()); for (int i = 0; i < paths.Length; i++) { if (!dependList.Contains(paths[i])) { dependList.Enqueue(paths[i]); } } }
private void BalanceIntakes() { Queue<Part> intakeQueue = new Queue<Part>( _editor.ship.Parts.Where( x => GetPartType( x ) == PartType.Intake ) // do not treat intakeandengine parts as intake but as engine .OrderByDescending( x => x.Modules.OfType<ModuleResourceIntake>().First().area ) ); // queue is easier to handle when distributing items to engines - this makes sure we can only handle a part once Utils.Log( "Intakes found: {0}", string.Join( ", ", intakeQueue.Select( x => x.partInfo.title + ": " + x.Modules.OfType<ModuleResourceIntake>().First().area ).ToArray() ) ); List<WeightedPartList> totalPartList = new List<WeightedPartList>(); // so far all jets have intakeair ratio of 15, so we treat jets, turbos and rapiers alike // TODO for future: take intakeair ratio into account. how exactly? I donno :) // handle engines grouped by type, so far its by placement order foreach ( Part part in _editor.ship.parts ) { if ( GetPartType( part ) == PartType.AirBreatherEngine ) { WeightedPartList wpl = new WeightedPartList(); wpl.AddPart( part ); totalPartList.Add( wpl ); } else if ( GetPartType( part ) == PartType.IntakeAndEngine ) { WeightedPartList wpl = new WeightedPartList(); wpl.IntakeAreaSum = part.Modules.OfType<ModuleResourceIntake>().First().area; // add intake area of part that has both intake and engine in one wpl.AddPart( part ); totalPartList.Add( wpl ); } } Utils.Log( "Jets found: {0}", string.Join( ", ", totalPartList.Select( x => x.PartList.First().partInfo.title ).ToArray() ) ); if ( intakeQueue.Count > 0 && totalPartList.Count > 0 ) { // strip ship from intakes and jets _editor.ship.parts.RemoveAll( x => intakeQueue.Contains( x ) ); Utils.Log( "removed intakes temporarily" ); _editor.ship.parts.RemoveAll( x => totalPartList.Select( y => y.PartList.First() ).Contains( x ) ); Utils.Log( "removed jets temporarily" ); int intakeCount = intakeQueue.Count; for ( int i = 0; i < intakeCount; i++ ) { Part part = intakeQueue.Dequeue(); totalPartList.Where( x => x.IntakeAreaSum == totalPartList.Min( y => y.IntakeAreaSum ) ).First().AddPart( part ); // WeightedPartList with the least IntakeAreaSum will get the next intake assigned } // go through all part lists, reverse them and add them back to ship foreach ( WeightedPartList partList in totalPartList ) { partList.PartList.Reverse(); _editor.ship.parts.AddRange( partList.PartList ); // add parts for engine and its intakes back to ship Utils.Log( "Intake/engine set: {0}, total intake area: {1}", string.Join( ", ", partList.PartList.Select( x => x.name ).ToArray() ), partList.IntakeAreaSum ); } Utils.Log( "Finished intakes - jets balance" ); } else { Utils.Log( "There are either no intakes or no engines" ); } }
private static void DumpMenus(string fileName) { if (File.Exists(fileName)) { LoadFuncNames(firmConsts.DFR_file); BinaryReader br = null; byte[] data; using (br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { data = br.ReadBytes((int)br.BaseStream.Length); } Queue<long> q = new Queue<long>(); List<long> resolved = new List<long>(); menus = new Dictionary<long, Struct6>(); elements = new Dictionary<long, Struct14>(); resolved.Add(0); uint addrOffset = firmConsts.Copy_Offset; foreach (var l in firmConsts.MenuRootList) { q.Enqueue(l); } while (q.Count > 0) { var addr = q.Dequeue(); var ss1 = string.Format("Addr 0x{0:X8}", addr); var s6 = new Struct6(data, addr, addrOffset); s6.ReadElements(data); resolved.Add(addr); menus.Add(addr, s6); foreach (var s14 in s6.menu_elements) { if (Array.IndexOf(firmConsts.MenuRootList, s14.menu_ptr) != -1) { } if (resolved.Contains(s14.menu_ptr) == false && q.Contains(s14.menu_ptr) == false) { if (s14.menu_ptr < firmConsts.Copy_To) { int az = 0; } var ss2 = string.Format("Menu 0x{0:X8} MenuEl 0x{1:X8} SubMenu 0x{2:X8}", addr, s14.mem_loc, s14.menu_ptr); q.Enqueue(s14.menu_ptr); } } } using (var sw = new StreamWriter(File.Open(fileName + ".menu.txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))) { using (var sw2 = new StreamWriter(File.Open(fileName + ".menu_sym.idc", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))) { sw2.WriteLine("#include <idc.idc>"); sw2.WriteLine("static MakeMenu(ref, txt, type) {"); sw2.WriteLine("\tMakeNameEx(ref, txt, 0 );"); sw2.WriteLine("\tif( type == 0) {"); sw2.WriteLine("\t\tMakeUnknown(ref, 0x20, 0 );"); sw2.WriteLine("\t\tMakeStructEx(ref, 0x20, \"Menu\");"); sw2.WriteLine("\t} else {"); sw2.WriteLine("\t\tMakeUnknown(ref, 0x10, 0 );"); sw2.WriteLine("\t\tMakeStructEx(ref, 0x10, \"MenuEl\");"); sw2.WriteLine("\t}"); sw2.WriteLine("}"); sw2.WriteLine("static main() {"); sw2.WriteLine(" Message(\"Menu Name: Start\\n\");"); foreach (var l in firmConsts.MenuRootList) { MenuDump(sw, sw2, "", l); } sw2.WriteLine("\tMessage(\"Menu Name: Done\\n\");"); sw2.WriteLine("}"); } } } }
public void Astar(string ftablename, string startpoint, string endpoint) { #region ʹ���ֵ䷽ʽ //����ʵ�ַ�ʽ��һ��ʹ���ֶδ洢��ͬ��ֵ������һ��ʹ�ù����Point��ʵ�� //ʹ���ֶη�ʽ��� Queue<int> Open = new Queue<int>(); //Queue<int> Open = new Queue<int>(); Queue<int> Close = new Queue<int>(); //��ǰ���·��ֵ Hashtable GScore = new Hashtable(); //��ǰ��㵽��ֹ���֮��Ĺ���ֵ Hashtable HScore = new Hashtable(); //�ܺ�=��ǰ���+����ֵ Hashtable FScore = new Hashtable(); //���ﵱǰ����ǰһ�����·���ϵĽ�� Hashtable ComeFrom = new Hashtable(); string sqlstr, tablename, tmpAdjVertex; DataTable VertexTable; int totalVertex, start, end, curVertex, adjVertex,tmpVertexId; string tmpVertex; string[] adjVertexes; tablename = GetLayerName(ftablename) + "_vertex_adjaction"; sqlstr = "select vertex_id,vertex_adj_id,line_adj_id from " + tablename + " " + "order by vertex_id asc"; VertexTable = postDB.DoQueryEx(sqlstr); totalVertex = VertexTable.Rows.Count; ////��ʼ�� start = int.Parse(startpoint); end = int.Parse(endpoint); //��ʼ�����뵽open������ Open.Enqueue(start); curVertex = start; for (int i = 0; i < totalVertex;i++ ) { tmpVertex = VertexTable.Rows[i]["vertex_id"].ToString(); tmpVertexId = Convert.ToInt32(tmpVertex); GScore.Add(tmpVertexId, MaxDistance); HScore.Add(tmpVertexId, 0.0); FScore.Add(tmpVertexId, MaxDistance); } GScore[curVertex] = (double)0.0; HScore[curVertex] = (double)GetHeuristic(curVertex, end, ftablename); FScore[curVertex] = (double)HScore[curVertex]; while (Open.Count > 0) { //��open����ȡ��FScore��С�Ľ�� //open������ֻ�洢�н���� curVertex = GetMinTotalCostVertex(Open, FScore); if (curVertex.Equals(end)) { //�������������·��д������ ConstructPath(ComeFrom,start,end,ftablename); return; } //��open������ɾ����Сֵ��Ӧ�Ľ�㣬����dequeue���� Open=RemoveMinFromOpen(Open, curVertex); Close.Enqueue(curVertex); tmpAdjVertex = VertexTable.Rows[curVertex - 1]["vertex_adj_id"].ToString(); adjVertexes = tmpAdjVertex.Split('_'); bool newIsBetter = false; double tentativeGScore; for (int i = 0; i < adjVertexes.Length; i++) { adjVertex = int.Parse(adjVertexes[i]); //��������close���У��������ٽ��в�����������һ�� if (! Close.Contains(adjVertex)) { tentativeGScore = (double)GScore[curVertex] + GetDistance(curVertex, adjVertex, ftablename); //�������open������ if (!Open.Contains(adjVertex)) { Open.Enqueue(adjVertex); newIsBetter = true; } else if (tentativeGScore < (double) GScore[adjVertex]) { newIsBetter = true; } if (newIsBetter) { ComeFrom[adjVertex] = curVertex; GScore[adjVertex] = tentativeGScore; HScore[adjVertex] = GetHeuristic(adjVertex, end, ftablename); FScore[adjVertex] = (double)GScore[adjVertex] + (double) HScore[adjVertex]; } } } } //�����õ�comefromΪ�գ���δ�ҵ���Ӧ��·�� //����������δ�õ����˵��δ�ҵ���ص�·�� #endregion }
/// <summary> /// </summary> /// <param name="method"> /// </param> /// <param name="stackCall"> /// </param> private void AddGenericSpecializedMethod(IMethod method, Queue<IMethod> stackCall) { if (this.usedGenericSpecialiazedMethods == null || method == null) { return; } if (!method.IsGenericMethod) { if (method.DeclaringType.IsGenericType && !stackCall.Contains(method)) { this.DiscoverRequiredTypesAndMethodsInMethod(method, stackCall); } return; } if (this.usedGenericSpecialiazedMethods.Contains(method)) { return; } this.usedGenericSpecialiazedMethods.Add(method); this.DiscoverRequiredTypesAndMethodsInMethod(method, stackCall); }
static void Main(string[] args) { byte right = 0; //massive index byte left = 1; byte down = 2; byte up = 3; Position[] directions = new Position[] { new Position(0, 1), // right new Position(0, -1), // left new Position(1, 0), // down new Position(-1, 0) // up }; int sleepTime = 100; int direction = right; Random randomNumberGenerator = new Random(); Console.BufferHeight = Console.WindowHeight; Position food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), //food randomNumberGenerator.Next(0, Console.WindowWidth)); Queue<Position> snakeElements = new Queue<Position>(); for (int i = 0; i <= 5; i++) { snakeElements.Enqueue(new Position(0, i)); } foreach (Position position in snakeElements) { Console.SetCursorPosition(position.cow, position.row); Console.Write("*"); } while (true) { Position snakeHead = snakeElements.Last(); Position nextDirection = directions[direction]; Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.cow + nextDirection.cow); if (snakeNewHead.row < 0 || snakeNewHead.cow < 0 || snakeNewHead.row >= Console.WindowHeight || snakeNewHead.cow >= Console.WindowWidth || snakeElements.Contains(snakeNewHead)) { Console.SetCursorPosition(0, 0); Console.BackgroundColor = ConsoleColor.DarkRed; Console.Beep(); Console.Beep(); Console.Beep(); Console.WriteLine("Game Over !!!"); Console.WriteLine("Your points are: {0}", snakeElements.Count - 6); return; } if (snakeNewHead.cow == food.cow && snakeNewHead.row == food.row) { // feeding the snake food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth)); Console.Beep(); sleepTime--; // speed up } else { // moving... snakeElements.Dequeue(); } if (Console.KeyAvailable) { ConsoleKeyInfo userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.LeftArrow) { if (direction != right) direction = left; } if (userInput.Key == ConsoleKey.RightArrow) { if (direction != left) direction = right; } if (userInput.Key == ConsoleKey.UpArrow) { if (direction != down) direction = up; } if (userInput.Key == ConsoleKey.DownArrow) { if(direction != up) direction = down; } } snakeElements.Enqueue(snakeNewHead); Console.Clear(); foreach (Position position in snakeElements) { Console.SetCursorPosition(position.cow, position.row); Console.Write("*"); } Console.SetCursorPosition(food.cow, food.row); Console.Write("@"); Thread.Sleep(sleepTime); } }
public override bool Contains(object obj) { lock (queue) { return(queue.Contains(obj)); } }
/// <summary>Searches for a match, beginning from a specified position.</summary> /// <param name="text">The text to match against.</param> /// <param name="startIndex">The starting position.</param> /// <param name="anchored">Set to <c>true</c> to force matches to start from <paramref name="startIndex"/>.</param> /// <returns>Result of the search.</returns> internal Match Find(string text, int startIndex, bool anchored) { int length = text.Length; if (Anchored) anchored = true; Stack<Match> avail = new Stack<Match>(); Queue<Match> active = new Queue<Match>(nTransitions); Match best = new Match(this, text, anchored); Match start = new Match(this, text, anchored); start.StateID = 0; start.Position = startIndex; if (!anchored) Scan(start); do { Match current; if (active.Count == 0 || active.Peek().Position > start.Position) current = start; else current = active.Dequeue(); Transition[] trans = States[current.StateID]; for (int i = 0; i < trans.Length; i++) { if (Evaluate(current, trans[i].instruction, trans[i].target, true)) { // don't duplicate work or run past the end of text if (current.Position <= length && !active.Contains(current, sameFinal)) { Match next; if (avail.Count == 0) next = new Match(this, text, anchored); else next = avail.Pop(); next.Copy(current); active.Enqueue(next); } } else if (Match.PosixPriority(current, best) > 0) best.Copy(current); Unevaluate(current); } if (current != start) avail.Push(current); else if (anchored || best.IsSuccess) start.Position = length; else { start.Position++; Scan(start); } } while (active.Count > 0 || start.Position < length); return best; }
public override bool Contains(Object obj) { lock (root) { return(_q.Contains(obj)); } }
public void DikkstraImpl(GraphImpl g, int start_vertex) { /*********************************************************************************************** * [1] Assign to every node a distance value. Set it to zero for our initial node and to infinity * for all other nodes. * [2] Mark all nodes as unvisited. Set initial node as current. * [3] For current node, consider all its unvisited neighbours and calculate their distance * (from the initial node). If this distance is less than the previously recorded distance * (infinity in the beginning, zero for the initial node), overwrite the distance. * [4] When we are done considering all neighbours of the current node, mark it as visited. * A visited node will not be checked ever again; its distance recorded now is final and minimal. * [5] Set the unvisited node with the smallest distance (from the initial node) as the next * "current node" and continue from step 3. * ~ Wiki * ********************************************************************************************/ Queue<int> visited_vertices = new Queue<int>(g.GetTotalNodes()); int[] distance_list = new Int32[g.GetTotalNodes()]; List<int> current_list = new List<int>(g.GetTotalNodes()); for (int z = 0; z < g.GetTotalNodes(); z++) { distance_list[z] = Int32.MaxValue; } distance_list[start_vertex] = 0; current_list.Add(start_vertex); Node start_node = g.searchNode(start_vertex); while (current_list.Count != 0) { List<int> pseudo_priority_list = new List<int>(current_list.Count); foreach(int value in current_list) { int xxx = distance_list[value]; pseudo_priority_list.Add(xxx); } int small = pseudo_priority_list.Min(); int index = pseudo_priority_list.IndexOf(small); int current_vertex = current_list[index]; Node current_node = g.searchNode(current_vertex); List<Edge> edge_list = new List<Edge>(); edge_list = current_node.GetEdgeList(); for (int z = 0; z < edge_list.Count; z++) { int r = edge_list[z]._dest.node_id; if (!visited_vertices.Contains(r) && !current_list.Contains(r)) { current_list.Add(r); } int edge1 = g.Edge_cost(start_node, current_vertex); if (edge1 == -1) { edge1 = distance_list[current_vertex]; } if (edge1 > distance_list[current_vertex]) { Console.WriteLine("For Edge1, Current vertex = " + current_vertex + " , R = " + r); edge1 = distance_list[current_vertex]; } int edge2 = g.Edge_cost(current_node, r); if (distance_list[r] > (edge1 + edge2)) { Console.WriteLine("For Edge2, Current vertex = " + current_vertex + " , R = " + r); distance_list[r] = edge1 + edge2; } } visited_vertices.Enqueue(current_vertex); current_list.Remove(current_vertex); } for (int z = 0; z < g.GetTotalNodes(); z++) { Console.WriteLine("shortest cost to reach " + z + " from " + start_vertex + " -> " + distance_list[z]); } }
static void Main() { byte right = 0, left = 1, down = 2, up = 3; int lastFoodTime = 0; int FoodDissapearTime = 8000; double NegativePoints = 0; Position[] directions = new Position[] { new Position(0, 1), // right new Position(0, -1), // left new Position(1, 0), // down new Position(-1, 0), // up }; double sleeptime = 100; int direction = 0; Random randomNumbersGenerator = new Random(); Console.BufferHeight = Console.WindowHeight; Position food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); List<Position> Obstacles = new List<Position>() { new Position(12,12), new Position(13,12), new Position(14,12), new Position(15,12), new Position(16,12), }; foreach (Position obstacle in Obstacles) { Console.ForegroundColor = ConsoleColor.Cyan; Console.SetCursorPosition(obstacle.col, obstacle.row); Console.Write("|"); } Queue<Position> snakeElements = new Queue<Position>(); for (int i = 0; i <= 5; i++) { snakeElements.Enqueue(new Position(0, i)); } foreach (Position position in snakeElements) { Console.SetCursorPosition(position.col, position.row); Console.ForegroundColor = ConsoleColor.White; Console.Write("*"); } do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); lastFoodTime = Environment.TickCount; Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); } while (snakeElements.Contains(food) || Obstacles.Contains(food)); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo userInput = Console.ReadKey(); while (Console.KeyAvailable) { userInput = Console.ReadKey(true); } if (userInput.Key == ConsoleKey.LeftArrow && direction != right) { direction = left; } if (userInput.Key == ConsoleKey.RightArrow && direction != left) { direction = right; } if (userInput.Key == ConsoleKey.UpArrow && direction != down) { direction = up; } if (userInput.Key == ConsoleKey.DownArrow && direction != up) { direction = down; } } Position snakeHead = snakeElements.Last(); Position nextDirection = directions[direction]; Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col); if (snakeNewHead.col < 0) snakeNewHead.col = Console.WindowWidth - 1; if (snakeNewHead.row < 0) snakeNewHead.row = Console.WindowHeight - 1; if (snakeNewHead.col >= Console.WindowWidth) snakeNewHead.col = 0; if (snakeNewHead.row >= Console.WindowHeight) snakeNewHead.row = 0; if (snakeElements.Contains(snakeNewHead) || Obstacles.Contains(snakeNewHead)) { Console.SetCursorPosition(0, 0); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Game over!"); int userpoints = (snakeElements.Count - 6) * 100 - (int)NegativePoints; userpoints = Math.Max(userpoints, 0); Console.WriteLine("Your points are: {0}", userpoints); Console.ReadLine(); return; } snakeElements.Enqueue(snakeNewHead); Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row); Console.ForegroundColor = ConsoleColor.Green; if (direction == left) { Console.Write("<"); } if (direction == right) { Console.Write(">"); } if (direction == down) { Console.Write("v"); } if (direction == up) { Console.Write("^"); } Console.SetCursorPosition(snakeHead.col, snakeHead.row); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("*"); if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) { // feeding do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(food) || Obstacles.Contains(food)); lastFoodTime = Environment.TickCount; Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); Position obstacle; do { obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(obstacle) || Obstacles.Contains(obstacle) || (food.row != obstacle.row && food.col != obstacle.col)); Obstacles.Add(obstacle); Console.SetCursorPosition(obstacle.col, obstacle.row); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("="); } else { //moving Position last = snakeElements.Dequeue(); Console.SetCursorPosition(last.col, last.row); Console.Write(" "); } if (Environment.TickCount - lastFoodTime >= FoodDissapearTime) { NegativePoints = NegativePoints + 50; Console.SetCursorPosition(food.col, food.row); Console.Write(" "); do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(food)); lastFoodTime = Environment.TickCount; Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); } Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); sleeptime -= 0.01; NegativePoints += 0.2; Thread.Sleep((int)sleeptime); } }
static void Main(string[] args) { byte right = 0; byte left = 1; byte down = 2; byte up = 3; Position[] directions = new Position[] { new Position(0, 1), //right new Position(0, -1), //left new Position(1, 0), // down new Position(-1, 0), //up }; int sleepTime = 100; int direction = right; //0 Random rand = new Random(); Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth; Position food = new Position(rand.Next(0,Console.WindowHeight), rand.Next(0, Console.WindowWidth)); Console.SetCursorPosition(food.col, food.row); Console.Write("$"); Queue<Position> snakeElements = new Queue<Position>(); for (int i=0; i<=5; i++) { snakeElements.Enqueue(new Position(0, i)); } foreach (Position position in snakeElements) { Console.SetCursorPosition(position.col, position.row); Console.WriteLine("*"); } while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.LeftArrow) { if (direction != right) direction = left; } if (userInput.Key == ConsoleKey.RightArrow) { if (direction !=left) direction = right; } if (userInput.Key == ConsoleKey.UpArrow) { if (direction!=down) direction = up; } if (userInput.Key == ConsoleKey.DownArrow) { if (direction!=up) direction = down; } } Position snakeHead = snakeElements.Last(); Position nextDirection = directions[direction]; Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col); if (snakeNewHead.row < 0 || snakeNewHead.col < 0 || snakeNewHead.row >= Console.WindowHeight || snakeNewHead.col >= Console.WindowWidth || snakeElements.Contains(snakeNewHead)) { Console.SetCursorPosition(0, 0); Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Game Over!"); Console.WriteLine("Your points are {0}", (snakeElements.Count-6) * 100); Console.ReadKey(); return; } snakeElements.Enqueue(snakeNewHead); if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) { food = new Position(rand.Next(0, Console.WindowHeight), rand.Next(0, Console.WindowWidth)); sleepTime--; } else { snakeElements.Dequeue(); } Console.Clear(); foreach (Position position in snakeElements) { Console.SetCursorPosition(position.col, position.row); Console.WriteLine("*"); } Console.SetCursorPosition(food.col, food.row); Console.Write("$"); Thread.Sleep(sleepTime); } }
/// <summary> /// lists the IDs of all qualifiers that are descendants of the given qualifier ID /// </summary> /// <param name="ancestorQualifierID">the ID of the qualifier whose descendants are sought</param> /// <param name="breadthFirst">if true, descendants are listed in breadth first order, otherwise depth first postorder, which happens to be the correct order for deleting subtrees in which all nodes are singly parented.</param> /// <returns>an array of Qualifier IDs of all descendant qualifiers</returns> public static int[] ListQualifierDescendants( int ancestorQualifierID, bool breadthFirst ) { ArrayList descendantList = new ArrayList(); //use a breadth first order approach //this code is still not optimized, i.e. we are searching the WHOLE hierarchy table even after //we have traversed it once. - Karim's notes if(breadthFirst) { Queue descendantQueue = new Queue(); int[] children = ListQualifierChildren(ancestorQualifierID); foreach (int child in children) { descendantList.Add(child); descendantQueue.Enqueue(child); } while( descendantQueue.Count > 0 ) { int[] moreDescendants = ListQualifierChildren(Convert.ToInt32(descendantQueue.Dequeue())); foreach(int grandchild in moreDescendants) { if(!descendantQueue.Contains(grandchild)) { descendantList.Add(grandchild); descendantQueue.Enqueue(grandchild); } } } } //use a depth first postorder method instead else { AuthorizationUtilities.QualifierPostOrder(ancestorQualifierID, descendantList); } return Utilities.ArrayListToIntArray(descendantList); }
/** * Finds a contiguos shape in the boolean image by doing breadth first search. * It also deletes the found pixels from the source image, cutting the shape out from the original. */ public static Shape breadthShapeExtendAndCut(bool[,] source, Point? firstPoint) { int i; int height = source.GetLength(0), width = source.Length / source.GetLength(0); int px, py, nx, ny; Point? head, neighbour; Queue<Point?> queue; int[] neighx = { -1, 0, 1, -1, 1, -1, 0, 1 }, neighy = { -1, -1, 1, 0, 0, 1, 1, 1 }; Shape shape = new Shape(); queue = new Queue<Point?>(); queue.Enqueue(firstPoint); while (queue.Count > 0) { head = queue.Dequeue(); shape.Add(head); px = head.Value.X; py = head.Value.Y; source[py, px] = false; for (i = 0; i < 8; i++) { nx = px + neighx[i]; ny = py + neighy[i]; neighbour = new Point(nx, ny); if ((nx >= 0) && (nx < width) && (ny >= 0) && (ny < height) && (source[ny, nx]) && (!shape.contains(neighbour)) && (!queue.Contains(neighbour))) { queue.Enqueue(neighbour); source[ny, nx] = false; } } } return shape; }
private void GetDeltaFinal(NFA nfa) { Queue newstates = new Queue (); Queue queue = new Queue (); Hashtable odelta = nfa.Delta; Hashtable ndelta = new Hashtable (); newstates.Enqueue (current_state); queue.Enqueue (current_state); while (queue.Count != 0) { string substate = (string) queue.Dequeue (); string [] states = substate.Split (':'); foreach (string sym in alph) { int icount = 0; string [] nstates = new string [states.Length]; foreach (string sub in states) { nstates [icount++] = (string) odelta [new Context (sub, sym)]; } string union = Union (nstates); if (union == null) union = "ERROR"; if (!newstates.Contains (union)) { newstates.Enqueue (union); queue.Enqueue (union); } ndelta.Add (new Context (substate, sym), union); } } this.delta = ndelta; int qcount = 0; string [] qstates = new string [newstates.Count]; foreach (object o in newstates) qstates [qcount++] = (string) o; this.states = qstates; string [] ofstates = nfa.FState; ArrayList list = new ArrayList (); foreach (string sub in states) foreach (string asub in ofstates) if (sub.IndexOf (asub) != -1) { list.Add (sub); break; } string [] farray = new string [list.Count]; list.CopyTo (farray); f_states = farray; }
/** * Extracts a horizontal or vertical shape of the original Shape. * The area of the new, smaller flat shape will be smaller thatn the areaLimit. * sizeLimit specifies the width of the flat, extracted shape. */ public static Shape reduceShapeHVAreaLimit(Shape originalShape, Point? firstPoint, int sizeLimit, bool horizontal, int areaLimit) { int px, py, nx, ny; int[] neighx = { -1, 0, 1, -1, 1, -1, 0, 1 }, neighy = { -1, -1, 1, 0, 0, 1, 1, 1 }; Shape reducedShape = new Shape(); Queue<Point?> queue = new Queue<Point?>(); if (originalShape == null) { return null; } if (!originalShape.contains(firstPoint)) { return null; } queue.Enqueue(firstPoint); while (true) { Point? head = queue.Dequeue(); reducedShape.Add(head); int reducedArea = reducedShape.Area; Point? shapeCenter = reducedShape.getCenter(); px = head.Value.X; py = head.Value.Y; for (int i = 0; i < 8; i++) { nx = px + neighx[i]; ny = py + neighy[i]; Point? neighbour = new Point(nx, ny); if ((originalShape.contains(neighbour)) && (!reducedShape.contains(neighbour)) && (!queue.Contains(neighbour)) && (queue.Count() + reducedArea < areaLimit) && (((horizontal) && (Math.Abs(nx - shapeCenter.Value.X) < sizeLimit)) || ((!horizontal) && (Math.Abs(ny - shapeCenter.Value.Y) < sizeLimit))) ) { queue.Enqueue(neighbour); } } if ((reducedArea > areaLimit) || (queue.Count == 0)) { break; } } return reducedShape; }
public static Shape reduceShapeToAreaAndRatio(Shape originalShape, Point? firstPoint, double ratioLimit, int areaLowerLimit, int areaHigherLimit) { int[] neighx = { -1, 0, 1, -1, 1, -1, 0, 1 }; int[] neighy = { -1, -1, 1, 0, 0, 1, 1, 1 }; if (ratioLimit <= 0) { return null; } double ratioLimitInv = 1 / ratioLimit; int px = 0, py = 0, nx, ny; Point? head, neighbour; Shape reducedShape = new Shape(); int reducedArea = 0; double reducedRatio = 1.0; Queue<Point?> queue = new Queue<Point?>(); if (originalShape == null) { return null; } if (!originalShape.contains(firstPoint)) { return null; } queue.Enqueue(firstPoint); while (true) { head = queue.Dequeue(); reducedShape.Add(head); reducedRatio = reducedShape.getAspectRatio(); reducedArea = reducedShape.Set.Count; py = head.Value.Y; for (int i = 0; i < 8; i++) { nx = px + neighx[i]; ny = py + neighy[i]; neighbour = new Point(nx, ny); if ((originalShape.contains(neighbour)) && (!reducedShape.contains(neighbour)) && (!queue.Contains(neighbour)) && (reducedArea + queue.Count < areaHigherLimit)) { queue.Enqueue(neighbour); } } /* * Stop condition. It's weird but it's faster */ if (!(queue.Count > 0)) { break; } else { if (reducedArea < areaLowerLimit) { continue; } else if (reducedArea > areaHigherLimit) { break; } else { if ((ratioLimitInv < reducedRatio) && (reducedRatio < ratioLimit)) { continue; } else { break; } } } } if ((reducedShape.Set.Count < areaLowerLimit) || ((ratioLimitInv < reducedRatio) && (reducedRatio < ratioLimit))) { return null; } return reducedShape; }
public void OnCycle() { try { Queue queue = new Queue(); lock (_cycleItems.SyncRoot) { while (_cycleItems.Count > 0) { IWiredItem wiredItem = (IWiredItem) _cycleItems.Dequeue(); IWiredCycler item = wiredItem as IWiredCycler; if (item == null) continue; IWiredCycler wiredCycler = item; if (!wiredCycler.OnCycle()) { if (!queue.Contains(item)) queue.Enqueue(item); } } } _cycleItems = queue; } catch (Exception e) { YupiLogManager.LogException(e, "Registered Wired Handling Exception.", "Yupi.Wired"); } }
public static void BuildSectorNodeNetwork(CommandEventArgs e) { if (m_Nodes == null) { try { Console.Write("Initializing SectorNodes..."); DateTime dt = DateTime.Now; m_Nodes = new SectorNode[Map.Felucca.Width >> Map.SectorShift, Map.Felucca.Height >> Map.SectorShift]; for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { SectorNode sn = new SectorNode(); sn.Point = Point3D.Zero; sn.Island = -1; sn.Links = new SectorNode[8]; sn.Distances = new int[8]; sn.NumLinks = 0; for (int sy = 0; sy < Map.SectorSize && sn.Point == Point3D.Zero; sy++) { for (int sx = 0; sx < Map.SectorSize && sn.Point == Point3D.Zero; sx++) { if (Map.Felucca.CanSpawnMobile((x << Map.SectorShift) + sx, (y << Map.SectorShift) + sy, Map.Felucca.GetAverageZ((x << Map.SectorShift) + sx, (y << Map.SectorShift) + sy))) { sn.Point = new Point3D((x << Map.SectorShift) + sx, (y << Map.SectorShift) + sy, Map.Felucca.GetAverageZ((x << Map.SectorShift) + sx, (y << Map.SectorShift) + sy)); } } } m_Nodes[x, y] = sn; } } Console.WriteLine("done in {0} seconds.", (DateTime.Now - dt).TotalSeconds); Console.Write("Computing SectorNode network..."); dt = DateTime.Now; Mobile m = new Server.Mobiles.WanderingHealer(); MovementPath mp = null; for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { if (m_Nodes[x, y].Point != Point3D.Zero) { m.MoveToWorld(m_Nodes[x, y].Point, Map.Felucca); if (x < (Map.Felucca.Width >> Map.SectorShift) - 1 && y > 0 && m_Nodes[x + 1, y - 1].Point != Point3D.Zero && (mp = new MovementPath(m, m_Nodes[x + 1, y - 1].Point)).Success) { m_Nodes[x, y].Links[m_Nodes[x, y].NumLinks] = m_Nodes[x + 1, y - 1]; m_Nodes[x, y].Distances[m_Nodes[x, y].NumLinks] = mp.Directions.Length; m_Nodes[x, y].NumLinks++; m_Nodes[x + 1, y - 1].Links[m_Nodes[x + 1, y - 1].NumLinks] = m_Nodes[x, y]; m_Nodes[x + 1, y - 1].Distances[m_Nodes[x + 1, y - 1].NumLinks] = mp.Directions.Length; m_Nodes[x + 1, y - 1].NumLinks++; } if (x < (Map.Felucca.Width >> Map.SectorShift) - 1 && m_Nodes[x + 1, y].Point != Point3D.Zero && (mp = new MovementPath(m, m_Nodes[x + 1, y].Point)).Success) { m_Nodes[x, y].Links[m_Nodes[x, y].NumLinks] = m_Nodes[x + 1, y]; m_Nodes[x, y].Distances[m_Nodes[x, y].NumLinks] = mp.Directions.Length; m_Nodes[x, y].NumLinks++; m_Nodes[x + 1, y].Links[m_Nodes[x + 1, y].NumLinks] = m_Nodes[x, y]; m_Nodes[x + 1, y].Distances[m_Nodes[x + 1, y].NumLinks] = mp.Directions.Length; m_Nodes[x + 1, y].NumLinks++; } if (x < (Map.Felucca.Width >> Map.SectorShift) - 1 && y < (Map.Felucca.Height >> Map.SectorShift) - 1 && m_Nodes[x + 1, y + 1].Point != Point3D.Zero && (mp = new MovementPath(m, m_Nodes[x + 1, y + 1].Point)).Success) { m_Nodes[x, y].Links[m_Nodes[x, y].NumLinks] = m_Nodes[x + 1, y + 1]; m_Nodes[x, y].Distances[m_Nodes[x, y].NumLinks] = mp.Directions.Length; m_Nodes[x, y].NumLinks++; m_Nodes[x + 1, y + 1].Links[m_Nodes[x + 1, y + 1].NumLinks] = m_Nodes[x, y]; m_Nodes[x + 1, y + 1].Distances[m_Nodes[x + 1, y + 1].NumLinks] = mp.Directions.Length; m_Nodes[x + 1, y + 1].NumLinks++; } if (y < (Map.Felucca.Height >> Map.SectorShift) - 1 && m_Nodes[x, y + 1].Point != Point3D.Zero && (mp = new MovementPath(m, m_Nodes[x, y + 1].Point)).Success) { m_Nodes[x, y].Links[m_Nodes[x, y].NumLinks] = m_Nodes[x, y + 1]; m_Nodes[x, y].Distances[m_Nodes[x, y].NumLinks] = mp.Directions.Length; m_Nodes[x, y].NumLinks++; m_Nodes[x, y + 1].Links[m_Nodes[x, y + 1].NumLinks] = m_Nodes[x, y]; m_Nodes[x, y + 1].Distances[m_Nodes[x, y + 1].NumLinks] = mp.Directions.Length; m_Nodes[x, y + 1].NumLinks++; } } } } m.Delete(); Console.WriteLine("done in {0} seconds.", (DateTime.Now - dt).TotalSeconds); Console.Write("Finding islands..."); dt = DateTime.Now; int nextIsland = 0; Queue open = new Queue(); ArrayList closed = new ArrayList(); for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { if (m_Nodes[x, y].Point == Point3D.Zero) continue; if (m_Nodes[x, y].Island == -1) { int island = nextIsland++; // now use dijkstra-style flood fill to find all connected nodes open.Clear(); closed.Clear(); open.Enqueue(m_Nodes[x, y]); while (open.Count > 0) { SectorNode sn = (SectorNode)open.Dequeue(); closed.Add(sn); sn.Island = island; for (int i = 0; i < sn.NumLinks; i++) if (!closed.Contains(sn.Links[i]) && !open.Contains(sn.Links[i])) open.Enqueue(sn.Links[i]); } } } } Console.WriteLine("done in {0} seconds.", (DateTime.Now - dt).TotalSeconds); } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("error!"); Console.WriteLine(ex); } } }
/// <summary> /// </summary> /// <param name="method"> /// </param> /// <param name="stackCall"> /// </param> private void AddGenericSpecializedMethod(IMethod method, Queue<IMethod> stackCall) { if (this.usedGenericSpecialiazedMethods == null || method == null) { return; } if (!method.IsGenericMethod) { if (method.DeclaringType.IsGenericType && !stackCall.Contains(method)) { this.DiscoverRequiredTypesAndMethodsInMethod(method, stackCall); } return; } if (method.IsGenericMethodDefinition || method.DeclaringType.IsGenericTypeDefinition || this.usedGenericSpecialiazedMethods.Contains(method)) { return; } Debug.Assert(!method.IsGenericMethodDefinition, "Generic Method Definition can't be used here"); Debug.Assert(!method.DeclaringType.IsGenericTypeDefinition, "Generic Type Definition can't be used here"); this.usedGenericSpecialiazedMethods.Add(method); this.DiscoverRequiredTypesAndMethodsInMethod(method, stackCall); }