private static void FillQueue(int firstX, int firstY, byte currColor, byte destColor) { Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>(); q.Enqueue(Tuple.Create(firstX, firstY)); var maxX = _data.GetLength(0); var maxY = _data.GetLength(1); while (q.Count > 0) { var point = q.Dequeue(); var x = point.Item1; var y = point.Item2; if (_data[x, y] == destColor) continue; if (_data[x, y] != currColor) continue; _data[x, y] = destColor; if (x + 1 < maxX) q.Enqueue(Tuple.Create(x + 1, y)); if (x - 1 >= 0) q.Enqueue(Tuple.Create(x - 1, y)); if (y + 1 < maxY) q.Enqueue(Tuple.Create(x, y + 1)); if (y - 1 >= 0) q.Enqueue(Tuple.Create(x, y - 1)); Display(_data); } }
private static IEnumerable<Type> getTypes(Type sourceType) { Queue<Type> pending = new Queue<Type>(); HashSet<Type> visited = new HashSet<Type>(); pending.Enqueue(sourceType); while (pending.Count != 0) { Type type = pending.Dequeue(); visited.Add(type); yield return type; if (type.BaseType != null) { if (!visited.Contains(type.BaseType)) { pending.Enqueue(type.BaseType); } } foreach (Type interfaceType in type.GetInterfaces()) { if (!visited.Contains(interfaceType)) { pending.Enqueue(interfaceType); } } } }
static void Main(string[] args) { // Stack - A LIFO collection Stack<string> stack = new Stack<string>(); stack.Push("A"); // Push adds to the stack stack.Push("B"); stack.Push("C"); stack.Push("D"); Console.WriteLine(stack.Peek()); // D - Peek returns the last added value without removing it Console.WriteLine(stack.Pop()); // D - Pop returna the last added value and removes it Console.WriteLine(stack.Peek()); // C // Queue - A FIFO collection Queue<string> queue = new Queue<string>(); queue.Enqueue("a"); // Enqueue adds to the queue queue.Enqueue("b"); queue.Enqueue("c"); queue.Enqueue("d"); Console.WriteLine(queue.Peek()); // a - Peek returns the beginning value without removing it Console.WriteLine(queue.Dequeue()); // a - Dequeue returns the beginning value and removes it Console.WriteLine(queue.Peek()); // b //-- Console.ReadKey(); }
public static Dictionary<AbstractState, Node> CreateGraph(Node root, params AbstractAction[] actions) { Dictionary<AbstractState, Node> uniqeNodes = new Dictionary<AbstractState, Node>(); uniqeNodes.Add(root.State, root); Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count > 0) { Node curNode = queue.Dequeue(); foreach (var action in actions) { AbstractState state = action.execute(curNode); if (state != null) if (!uniqeNodes.ContainsKey(state)) { Node newNode = new Node(state); curNode.Children.Add(new Tuple<Node, AbstractAction>(newNode, action)); uniqeNodes.Add(state, newNode); queue.Enqueue(newNode); } else { curNode.Children.Add(new Tuple<Node, AbstractAction>(uniqeNodes[state], action)); } } } return uniqeNodes; }
private void queueButton_Click(object sender, EventArgs e) { Queue fila = new Queue(); //Adicionando itens fila.Enqueue("Gabriela"); fila.Enqueue("Rafael"); fila.Enqueue("Thiago"); //Exibindo os itens da coleção foreach (string elemento in fila) { listBox1.Items.Add(elemento); } listBox1.Items.Add("--------------"); //Exibindo o item primeiro da fila listBox1.Items.Add("primeiro da fila"); listBox1.Items.Add(fila.Peek()); listBox1.Items.Add("--------------"); //Retirando um elemento da fila (primeiro da fila) fila.Dequeue(); //Exibindo o item primeiro da fila listBox1.Items.Add("primeiro da fila"); listBox1.Items.Add(fila.Peek()); }
static void Mai(string[] args) { //4 algoritmos para almacenar informacion. //1.Colas (FIFO) //2.Pilas (LIFO) //3.Listas (Array dinamico, se accede a su informacion por el indice) //4.Diccionarios () //5.Set() //Cola Queue q=new Queue(); q.Enqueue("A"); q.Enqueue(new Persona());//Enqueue para meter datos Console.WriteLine(q.Dequeue());//El dequeue para sacar datos Console.WriteLine(q.Dequeue()); ArrayList l=new ArrayList(); l.Add(new Persona()); l.Add(new Persona()); l.Add(new Persona()); l.Add(new Persona()); l.Add("Pepo"); l.Add(23); l.Add(new Persona()); l.Add(new Persona()); Console.WriteLine(l[4]); Console.ReadLine(); }
public IEnumerator GenerateWorld() { bool flip = false; Queue<Node> current_node = new Queue<Node>(); Queue<Node> tree = new Queue<Node>(); current_node.Enqueue(root); tree.Enqueue(root); for(int i=0;i<depth;i++){ for(int j=0;j<current_node.Count;j++){ flip = !flip; current_node.Peek().Split(flip); current_node.Enqueue(current_node.Peek().leafs[0]); current_node.Enqueue(current_node.Peek().leafs[1]); tree.Enqueue(current_node.Peek().leafs[0]); tree.Enqueue(current_node.Peek().leafs[1]); current_node.Dequeue(); } } for(int i=0;i<tree.Count;i++){ if(tree.Peek().initAutomata()){ progress+=1/tree.Count; tree.Dequeue(); } } yield return null; }
private static void AddQueuedActionsToLoadingQueue() { LoadingManager instance = Singleton<LoadingManager>.instance; object obj = typeof(LoadingManager).GetFieldByName("m_loadingLock").GetValue(instance); while (!Monitor.TryEnter(obj, SimulationManager.SYNCHRONIZE_TIMEOUT)) { } try { FieldInfo fieldByName = typeof(LoadingManager).GetFieldByName("m_mainThreadQueue"); Queue<IEnumerator> queue1 = (Queue<IEnumerator>) fieldByName.GetValue(instance); if (queue1 == null) { return; } Queue<IEnumerator> queue2 = new Queue<IEnumerator>(queue1.Count + 1); queue2.Enqueue(queue1.Dequeue()); do ; while (!Monitor.TryEnter(QUEUE_LOCK, SimulationManager.SYNCHRONIZE_TIMEOUT)); try { while (ACTION_QUEUE.Count > 0) { queue2.Enqueue(ACTION_QUEUE.Dequeue()); } } finally { Monitor.Exit(QUEUE_LOCK); } while (queue1.Count > 0) { queue2.Enqueue(queue1.Dequeue()); } fieldByName.SetValue(instance, queue2); } finally { Monitor.Exit(obj); } }
/// <summary> /// Creates the points. /// </summary> /// <returns>GestChecker wtih points</returns> public GameObject createPoints() { //int count = transform.childCount; Queue<Transform> fronta = new Queue<Transform>(); //Queue<Transform> fronta2 = new Queue<Transform>(); fronta.Enqueue(transform); GameObject checkerClone = (GameObject) GameObject.Instantiate(checker,transform.position,Quaternion.identity); GameObject fig = figureCopy(); //fronta2.Enqueue(fig.transform.GetChild(0)); fig.transform.parent = checkerClone.transform; while(fronta.Count>0) { Transform last = fronta.Dequeue(); //Transform last2 = fronta2.Dequeue(); int num = last.childCount; for(int i=0; i<num;i++) { fronta.Enqueue(last.GetChild(i)); //fronta2.Enqueue(last2.GetChild(i)); } GameObject clone = (GameObject) GameObject.Instantiate(checke,last.position,Quaternion.identity); clone.name = last.name+"-check"; clone.transform.parent = checkerClone.transform; // last2.transform.position = last.transform.position; //last2.transform.rotation = last.transform.rotation; } return checkerClone; }
public IList BreadthFirstSearch(BatteryStation s) { UnmarkAll(); IList l = new ArrayList(); Queue<BatteryStation> q = new Queue<BatteryStation>(); q.Enqueue(s); l.Add(s); s.Mark = true; while (q.Count > 0) { BatteryStation n = q.Dequeue(); BatteryStation c = null; while ((c = GetNextUnMarked(GetAdjacencies(n))) != null) { c.Mark = true; q.Enqueue(c); l.Add(c); } } return l; }
public void SimpleStartToEndScenarioTest() { // Setup Fakes var fakeRtEvents = new FakeRTEvents(); var fakeDecalEvents = new FakeDecalEventsProxy(); Queue<Location> locationResults = new Queue<Location>(); locationResults.Enqueue(new Location(0, 0, 1, 0, 0)); locationResults.Enqueue(new Location(0, 0, 2, 0, 0)); locationResults.Enqueue(new Location(0, 0, 3, 0, 0)); locationResults.Enqueue(new Location(0, 0, 4, 0, 0)); for (int i = 0; i < JumpRecorder.NumberOfConsecutiveZCoordsSameToSingleLand; i++) { locationResults.Enqueue(new Location(0, 0, 5, 0, 0)); } List<SelfJumpCompleteEventArgs> cachedCompleteCallValues = new List<SelfJumpCompleteEventArgs>(); // Workflow to Test JumpRecorder recorder = new JumpRecorder(fakeRtEvents, fakeDecalEvents, e => cachedCompleteCallValues.Add(e), () => locationResults.Dequeue()); var initialJumpData = new JumpData(new Location(0, 0, 0, 0, 0), 0.0, 0.0); Assert.IsFalse(recorder.IsRecording); fakeRtEvents.FireSelfJump(new JumpEventArgs(0, initialJumpData, 0, 0)); Assert.IsTrue(recorder.IsRecording); fakeDecalEvents.FireRenderFrame(new EventArgs()); fakeDecalEvents.FireRenderFrame(new EventArgs()); fakeDecalEvents.FireRenderFrame(new EventArgs()); // We should not have landed yet Assert.IsTrue(recorder.IsRecording); Assert.AreEqual(0, cachedCompleteCallValues.Count); fakeDecalEvents.FireRenderFrame(new EventArgs()); for (int i = 0; i < JumpRecorder.NumberOfConsecutiveZCoordsSameToSingleLand; i++) { fakeDecalEvents.FireRenderFrame(new EventArgs()); } // Now we should have landed Assert.IsFalse(recorder.IsRecording); Assert.AreEqual(1, cachedCompleteCallValues.Count); Assert.AreEqual(initialJumpData, cachedCompleteCallValues[0].JumpData); Assert.AreEqual(4 + JumpRecorder.NumberOfConsecutiveZCoordsSameToSingleLand, cachedCompleteCallValues[0].Trajectory); Assert.AreEqual(1, cachedCompleteCallValues[0].Trajectory[0].Z); Assert.AreEqual(5, cachedCompleteCallValues[0].Trajectory.Last().Z); Assert.AreEqual(5, cachedCompleteCallValues[0].LandingLocation.Z); }
public void printTreeByLevel(Node root) { if (root==null) return; Queue cur = new Queue(); Queue next = new Queue(); cur.Enqueue(root); while ((cur.Count > 0) || (next.Count > 0)) { if (cur.Count > 0) { Node temp = (Node)cur.Dequeue(); Console.Write("{0}->", temp.value); if (temp.right != null) next.Enqueue(temp.right); if (temp.left != null) next.Enqueue(temp.left); } else { Console.WriteLine(); Queue tq = next; next = cur; cur = tq; } } }
public void BFS(VNode v) { /*使用队列来实现广度优先搜索 */ Queue<VNode> q = new Queue<VNode>(); v.Visited = true; q.Enqueue(v); Console.WriteLine("Visit:{0}", v.Data); while (q.Count > 0) { var vnode = q.Dequeue(); var enode = vnode.FirstEdge; while (null != enode) { if (!enode.Adj.Visited) { enode.Adj.Visited = true; Console.WriteLine("Visit:{0}", enode.Adj.Data); q.Enqueue(enode.Adj); } enode = enode.Next; } } }
public int calculateSum() { InOrder id = new InOrder(); Node root = id.createTree(2); Queue myQueue = new Queue(); myQueue.Enqueue(root); int sum = 0; while (myQueue.Count > 0) { Node top = (Node)myQueue.Dequeue(); if ((top.left == null) && (top.right == null)) { sum += top.value; } if (top.left != null) { top.left.value = top.value * 10 + top.left.value; myQueue.Enqueue(top.left); } if (top.right != null) { top.right.value = top.value * 10 + top.right.value; myQueue.Enqueue(top.right); } } return sum; }
private Renderer[] GetRenderersWithoutInstancesInChildren() { List<Renderer> renderers = new List<Renderer>(); Queue<Transform> transformQueue = new Queue<Transform>(); // enqueue children first foreach (Transform child in transform) { transformQueue.Enqueue(child); } while (transformQueue.Count > 0) { Transform t = transformQueue.Dequeue(); GameObject g = t.gameObject; RendererInstance instance = g.GetComponent<RendererInstance>(); if (instance == null) { Renderer r = g.GetComponent<Renderer>(); if (r != null) { renderers.Add(r); } foreach (Transform child in t) { transformQueue.Enqueue(child); } } } return renderers.ToArray(); }
static void Mai(string[] args) { //Cola. Queue q = new Queue(); q.Enqueue("A"); q.Enqueue(new Persona()); Console.WriteLine(q.Dequeue()); Console.WriteLine(q.Dequeue()); //Es lo mas parecido a un array dinamico ArrayList p = new ArrayList(); p.Add(new Persona()); p.Add(new Persona()); p.Add("Pepe"); p.Add(new Persona()); p.Add(new Persona()); p.Add(""); p.Add(new Persona()); Console.WriteLine(p[2]); Console.ReadLine(); //Diccionario. Estructura de datos que se almacena con claves. //Para usarlo llamaremos directamente a la clave. }
public static void Main() { const int multiplier = 2; const int firstAddend = 1; const int secondAddend = 2; int sequenceLength = 50; int currentNumber = int.Parse(Console.ReadLine()); var sequence = new Queue<int>(); var tempQueue = new Queue<int>(); sequence.Enqueue(currentNumber); tempQueue.Enqueue(currentNumber); while (sequence.Count < sequenceLength) { currentNumber = tempQueue.Dequeue(); sequence.Enqueue(currentNumber + firstAddend); sequence.Enqueue(multiplier * currentNumber + firstAddend); sequence.Enqueue(currentNumber + secondAddend); tempQueue.Enqueue(currentNumber + firstAddend); tempQueue.Enqueue(multiplier * currentNumber + firstAddend); tempQueue.Enqueue(currentNumber + secondAddend); } while (sequenceLength > 0) { Console.Write(sequence.Dequeue() + " "); sequenceLength--; } }
//Main_7_9_6 public static void Main_7_9_6() { Queue myQueue = new Queue(); //��Queueβ�����Ԫ�� myQueue.Enqueue("��"); myQueue.Enqueue("��"); myQueue.Enqueue("˭"); //����Queueu��ʼ��Ԫ�� Console.WriteLine(myQueue.Peek()); //���ز��Ƴ�Queue��ʼ��Ԫ�� myQueue.Dequeue(); //����Queue foreach (object o in myQueue) Console.WriteLine(o.ToString()); Stack myStack = new Stack(); //��Stack��������Ԫ�� myStack.Push("��"); myStack.Push("��"); myStack.Push("˭"); //����Stack������Ԫ�� Console.WriteLine(myStack.Peek()); //���ز��Ƴ�Stack������Ԫ�� myStack.Pop(); //����Stack foreach (object o in myStack) Console.WriteLine(o.ToString()); }
private void ApplyDynamicUpdateMode(Activity seedActivity) { Queue<Activity> queue = new Queue<Activity>(); queue.Enqueue(seedActivity); while (queue.Count > 0) { Activity activity = queue.Dequeue(); activity.Readonly = true; activity.DynamicUpdateMode = true; foreach (DependencyProperty property in activity.MetaDependencyProperties) { if (activity.IsBindingSet(property)) { ActivityBind binding = activity.GetBinding(property); if (binding != null) { binding.DynamicUpdateMode = true; } } } if (activity is CompositeActivity) { CompositeActivity activity2 = activity as CompositeActivity; activity2.Activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnActivityListChanged); foreach (Activity activity3 in ((CompositeActivity) activity).Activities) { queue.Enqueue(activity3); } } } }
void IAssemblerComponent.AddDocument(IPipelineContext pContext, IBaseMessage pInMsg) { if (this.GetFault(pInMsg) != null) { qOutputMsgs.Enqueue(pInMsg); } else { MultipartMessageDefinition tempMessage = MultipartMessageManager.GenerateFromMessage(pInMsg); StringWriter sw = new StringWriter(); XmlSerializer ser = new XmlSerializer(typeof(MultipartMessageDefinition), Constants.SUBMISSION_NAMESPACE); ser.Serialize(sw, tempMessage); byte[] arrByte = System.Text.Encoding.UTF8.GetBytes(sw.ToString().Replace("utf-16", "utf-8")); //GetBytes(sw.ToString().Replace("utf-16", "utf-8")); //GetBytes(sw.ToString()); MemoryStream tempStream = new MemoryStream(arrByte); tempStream.Seek(0, SeekOrigin.Begin); IBaseMessage outMsg = pContext.GetMessageFactory().CreateMessage(); IBaseMessagePart outPart = pContext.GetMessageFactory().CreateMessagePart(); outPart.Data = tempStream; outPart.Charset = "utf-8"; outMsg.AddPart("ConstructedPart", outPart, true); //outMsg.BodyPart.Data = tempStream; outMsg.Context = pInMsg.Context; outMsg.Context.Promote(BTSProperties.messageType.Name.Name, BTSProperties.messageType.Name.Namespace, "http://BizWTF.Mocking.Schemas.Submission#MultipartMessage"); qOutputMsgs.Enqueue(outMsg); pContext.ResourceTracker.AddResource(tempStream); } }
static void Main(string[] args) { //New Queue of Integers Queue<int> queue = new Queue<int>(); queue.Enqueue(5); queue.Enqueue(10); queue.Enqueue(15); queue.Enqueue(20); /*Create new array with length equal to Queue's element count*/ int[] array = new int[queue.Count]; //Copy the Queue to the Array queue.CopyTo(array, 0); //Loop through and display int[] in order Console.WriteLine("Array: "); for (int i=0; i < array.Length; i++) { Console.WriteLine(array[i]); } //Loop through int array in reverse order Console.WriteLine("Array reverse order: "); for (int i = array.Length -1; i >= 0; i--) { Console.WriteLine(array[i]); } }
/// <summary> /// returns true if path exists from startVertex to endVertex /// </summary> private bool breadthFirstSearch(object startVertex, object endVertex) { var queue = new Queue(); var vertexQueue = new Queue(); bool found = false; graph.clearMarks(); queue.Enqueue(startVertex); do { object vertex = queue.Dequeue(); if (vertex == endVertex) found = true; else { if (!graph.isMarked(vertex)) { graph.markVertex(vertex); vertexQueue = graph.getToVertices(vertex); while (vertexQueue.Count > 0) { object item = vertexQueue.Dequeue(); if (!graph.isMarked(item)) queue.Enqueue(item); } } } } while (queue.Count > 0 & !found); return found; }
/*public static XmlDocument sendsms(String username, String password, String message, String target, String ext, String send_time) { string soapStr = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:yc=\"http://yc\" xmlns:xsd=\"http://yc/xsd\">" +" <soapenv:Header/>" + "<soapenv:Body>" + "<yc:sendsms>" + "<yc:username>"+username+"</yc:username>" + "<yc:password>"+password+"</yc:password>" + "<yc:_SendRequset>" + "<xsd:ext>"+ext+"</xsd:ext>" + "<xsd:message>"+message+"</xsd:message>" + "<xsd:send_time>"+send_time+"</xsd:send_time>" + "<xsd:target>"+target+"</xsd:target>" + "</yc:_SendRequset>" + "</yc:sendsms>" + "</soapenv:Body>" + "</soapenv:Envelope>"; return WebSrvCaller.QuerySoapWebService(soapURL, "sendsms", null, WSDLURL, soapStr); }*/ public static XmlDocument checkBalance(string username, string password) { Queue parsQ = new Queue(); parsQ.Enqueue(new DictionaryEntry("username", username)); parsQ.Enqueue(new DictionaryEntry("password", password)); return WebSrvCaller.QuerySoapWebService(soapURL, "checkBalance", parsQ, WSDLURL); }
private void QueueTest() { Queue queue = new Queue(); queue.Enqueue( CAR_BANK[0] ); queue.Enqueue( CAR_BANK[1] ); queue.Enqueue( CAR_BANK[2] ); ((Car)queue.Peek()).Display(); DeQueued( (Car)queue.Dequeue() ); ((Car)queue.Peek()).Display(); DeQueued( (Car)queue.Dequeue() ); ((Car)queue.Peek()).Display(); DeQueued( (Car)queue.Dequeue() ); try { ((Car)queue.Peek()).Display(); DeQueued( (Car)queue.Dequeue() ); } catch (Exception e) { Console.WriteLine( "Error!:{0}", e.Message ); } }
public IList<IList<int>> LevelOrderBottom(TreeNode root) { IList<IList<int>> result = new List<IList<int>>(); if (root == null) return result; Stack<IList<int>> stack = new Stack<IList<int>>(); Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { IList<int> items = new List<int>(); int num = queue.Count; for (int i = 0; i < num; i++) { TreeNode node = queue.Dequeue(); items.Add(node.val); if (node.left != null) queue.Enqueue(node.left); if (node.right != null) queue.Enqueue(node.right); } stack.Push(items); } while (stack.Count > 0) result.Add(stack.Pop()); return result; }
static void Main(string[] args) { //ArrayList ArrayList arrayList = new ArrayList(); arrayList.Add("First item"); arrayList.Add(5); arrayList.Add('c'); foreach (var item in arrayList) { Console.WriteLine("Element of arrayList: {0}", item); } //HashTable Hashtable hashtable = new Hashtable(); hashtable.Add(0, "Zero item"); hashtable[1] = "First item"; hashtable["2"] = "Second item"; hashtable[Guid.NewGuid()] = "Third item"; ICollection keys = hashtable.Keys; foreach (var key in keys) { Console.WriteLine("Key: {0}, Value: {1}", key, hashtable[key]); } //SortedList SortedList sl = new SortedList(); sl.Add("007", "Ritesh Saikia"); sl.Add("001", "Zara Ali"); sl.Add("002", "Abida Rehman"); sl.Add("003", "Joe Holzner"); sl.Add("004", "Mausam Benazir Nur"); sl.Add("006", "M. Amlan"); sl.Add("005", "M. Arif"); ICollection slValues = sl.Values; foreach (var s in slValues) { Console.WriteLine("SortedList value: {0}", s); } //Queue is FIFO: First in First out Queue que = new Queue(); que.Enqueue("Student_1"); que.Enqueue(5); que.Enqueue("Student_2"); que.Enqueue("Student_3"); Console.WriteLine(que.Dequeue().ToString()); Console.WriteLine(que.Dequeue().ToString()); // Stack is FILO: First in Last out Stack StackPop = new Stack(); StackPop.Push("Student_1"); StackPop.Push("Student_2"); StackPop.Push("Student_3"); Console.WriteLine(StackPop.Pop().ToString()); Console.WriteLine(StackPop.Pop().ToString()); Console.ReadLine(); }
private static Activity GetActivity(Activity containerActivity, string id) { if (containerActivity != null) { Queue queue = new Queue(); queue.Enqueue(containerActivity); while (queue.Count > 0) { Activity activity = (Activity) queue.Dequeue(); if (activity.Enabled) { if (activity.QualifiedName == id) { return activity; } if (activity is CompositeActivity) { foreach (Activity activity2 in ((CompositeActivity) activity).Activities) { queue.Enqueue(activity2); } } } } } return null; }
public int[] getPath(DirectedGraph g, int vertex) { Queue<int> q = new Queue<int>(); q.Enqueue(vertex); //set up the entire distance matrix with -1 except for the vertex node for (int i = 0; i < g.getTotalVertices(); i++) { distanceMatrix[i] = -1; } //set up current vertex with 0 because there will be no distance distanceMatrix[vertex] = 0; while (q.Count > 0) { int v = q.Dequeue(); Console.Write(v); //this is the breadth first traversal ArrayList adjacent = g.Adjacent(v); //loop through all the adjacent nodes, if the currentVertex is still -1, then go in and do process for (int i = 0; i < adjacent.Count; i++) { int currentVertex = (int)adjacent[i]; if (distanceMatrix[currentVertex] == -1) { //add one to the distanceMatrix here because it's going to be from v to the current path distanceMatrix[currentVertex] = distanceMatrix[v] + 1; pathMatrix[currentVertex] = v; q.Enqueue(currentVertex); } } } return distanceMatrix; }
public static MemberInfo[] GetProperties(Type type) { var flags = BindingFlags.Public | BindingFlags.Instance; if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties(flags) .Where(o => !o.HasAttribute<HideInInspector>()) .Where(o => !o.Module.Name.Contains("UnityEngine")) .OrderBy(o => o.Name); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } else { var propertyInfos = new List<MemberInfo>(); var props = type.GetProperties(flags).Where(o => !o.HasAttribute<HideInInspector>() && !o.Module.Name.Contains("UnityEngine")).OrderBy(o => o.Name); foreach (var prop in props) { if (prop.IsSpecialName) continue; propertyInfos.Add(prop); } var fields = type.GetFields(flags).Where(o => !o.HasAttribute<HideInInspector>() && !o.Module.Name.Contains("UnityEngine")).OrderBy(o => o.Name); foreach (var prop in fields) { propertyInfos.Add(prop); } return propertyInfos.ToArray(); } }
public static void Mai(string[] args) { Queue colaG=new Queue(); colaG.Enqueue("Hola"); colaG.Enqueue("Soy"); colaG.Enqueue(new Persoona() {Apellidos = "Gomez", Nombre = "Pepe"}); colaG.Enqueue(22); foreach (var elem in colaG) { // var p = elem as persoona; // //si p es diferente de null, hazlo. // if (p !=null) // Console.WriteLine(p.Apellidos); // else // { Console.WriteLine(elem); } // de esta manera obtendremos listas de objetos de manera inversa con Push Stack<Persoona> stackP = new Stack<Persoona>(); //De esta manera obtendremos listas de objetos //Queue<Persoona> colaP = new Queue<Persoona>(); stackP.Push(new Persoona() //colaP.Enqueue(new Persoona() { Apellidos = "Gomez", Nombre ="Albero", }); stackP.Push(new Persoona() //colaP.Enqueue(new Persoona() { Apellidos = "Jimenez", Nombre = "Luis", }); stackP.Push(new Persoona() //colaP.Enqueue(new Persoona() { Apellidos = "Dominguez", Nombre = "Eva", }); //foreach (var elem in colaP) //{ // Console.WriteLine(elem); //} foreach (var elem in stackP) { Console.WriteLine(elem); } Console.ReadLine(); }
public static void Mai(string[] args) { Queue colaG = new Queue(); colaG.Enqueue("Hola"); colaG.Enqueue("soy"); colaG.Enqueue(new Persona() { Apellidos = "Gomez", Nombre = "Pepe" }); colaG.Enqueue(28); foreach (var elem in colaG) { // SAFE CASTING: si no es Persona, p vale NULL var p = elem as Persona; if (p != null) Console.WriteLine(((Persona)elem).Nombre); else Console.WriteLine(elem); } //Modificando el ToStringo de la clase Persona, simplifica la recuperación de datos foreach (var elem in colaG) { Console.WriteLine(elem); } /*GENERIX, solo van a poder almacenar los objetos del tipo que se le indique*/ /*COLA*/ Queue<Persona> colaP = new Queue<Persona>(); colaP.Enqueue(new Persona() { Apellidos = "Dominguez", Nombre = "Eva" }); colaP.Enqueue(new Persona() { Apellidos = "Gonzalez", Nombre = "Andrez" }); colaP.Enqueue(new Persona() { Apellidos = "Llorente", Nombre = "Manuel" }); foreach (var elem in colaP) { Console.WriteLine(elem.Nombre); } /*PILA*/ Stack<Persona> pilaP = new Stack<Persona>(); pilaP.Push(new Persona() { Apellidos = "Dominguez", Nombre = "Eva" }); pilaP.Push(new Persona() { Apellidos = "Gonzalez", Nombre = "Andrez" }); pilaP.Push(new Persona() { Apellidos = "Llorente", Nombre = "Manuel" }); foreach (var elem in pilaP) { Console.WriteLine(elem.Nombre); } Console.ReadLine(); }
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(); }
public static void Main(string[] args) { var q1 = new System.Collections.Queue(); q1.Enqueue(1); q1.Enqueue(2); q1.Enqueue(3); Console.WriteLine(q1.Dequeue() + ""); Console.WriteLine(q1.Dequeue() + ""); Console.WriteLine(q1.Dequeue()); }
static void Main(string[] args) { System.Collections.Queue q = new System.Collections.Queue(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); ReverseOfQueue(q); Console.WriteLine("Queue elements are:"); foreach (int i in q) { Console.Write(i + " "); } }
public static void Main(string[] args) { System.Collections.Queue kö = new System.Collections.Queue(10); { kö.Enqueue(1); kö.Enqueue(2); kö.Enqueue(3); kö.Enqueue(15); kö.Enqueue(null); kö.Enqueue(20); kö.Enqueue("test string"); kö.Enqueue(25); Console.WriteLine($"Totalt antal element = {kö.Count}"); //Räknar antal element i kön Console.WriteLine(kö.Peek()); //Kollar elementen i kön enligt ordning kö.Dequeue(); Console.WriteLine(kö.Peek()); kö.Dequeue(); Console.WriteLine(kö.Peek()); kö.Dequeue(); kö.Dequeue(); Console.WriteLine(kö.Peek()); kö.Dequeue(); kö.Dequeue(); Console.WriteLine(kö.Peek()); kö.Dequeue(); Console.WriteLine(kö.Peek()); Console.WriteLine($"Antal element efter = {kö.Count}"); // Visar att elementen tagits bort kö.Clear(); } }
public static void SamplesQueueMain() { // Creates and initializes a new Queue. System.Collections.Queue myQ = new System.Collections.Queue(); myQ.Enqueue("Hello"); myQ.Enqueue("World"); myQ.Enqueue("!"); // Displays the properties and values of the Queue. Console.WriteLine("myQ"); Console.WriteLine("\tCount: {0}", myQ.Count); Console.Write("\tValues:"); PrintValues(myQ); }
private void GetFileContents(string fileName) { try { if (this._scriptBatchContents == null) { this._scriptBatchContents = new System.Collections.Queue(); } StreamReader fileReader = new StreamReader(fileName); StringBuilder currentScript = new StringBuilder(); string currentLine = ""; Regex rexLn = new Regex("--", RegexOptions.Singleline); Regex rexGo = new Regex("^go$", RegexOptions.IgnoreCase); bool insertionFlag = false; currentLine = fileReader.ReadLine(); while (!(currentLine == null)) { if (!rexLn.Match(currentLine).Success) { if (rexGo.Match(currentLine).Success) { _scriptBatchContents.Enqueue(currentScript.ToString()); insertionFlag = true; currentScript = new StringBuilder(); } else { currentScript.Append(currentLine); currentScript.Append("\r\n"); } } currentLine = fileReader.ReadLine(); } if (!insertionFlag) { _scriptBatchContents.Enqueue(currentScript.ToString()); } } catch (Exception ex) { throw (ex); } }
public void Push(object msg) { m_logQueue.Enqueue(msg); for (; m_logQueue.Count >= m_capacity;) { m_logQueue.Dequeue(); } }
/// <summary> /// Method Enqueue /// </summary> public void Enqueue(Apache.NMS.IMessage message) { lock (semaphore) { queue.Enqueue(message); messageReceivedEventHandle.Set(); } }
/// <summary> /// called by the messaging engine when a new message arrives /// </summary> /// <param name="pc">the pipeline context</param> /// <param name="inmsg">the actual message</param> public void Disassemble(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // // TODO: implement message retrieval logic IBaseMessagePart Body = inmsg.BodyPart; if (Body != null) { Stream originalStream = Body.GetOriginalDataStream(); if (originalStream != null) { var xml = XElement.Load(originalStream); var rootElement = xml.Name; // Child elements from source file to split by. var childNodes = xml.Descendants(this.DescendantElement); // This is the total number of elements to be sliced up into // separate files. int cnt = childNodes.Count(); var skip = 0; var take = this.BatchSize; var fileno = 0; // Split elements into chunks and save to disk. while (skip < cnt) { // Extract portion of the xml elements. var c1 = childNodes .Skip(skip) .Take(take); // Setup number of elements to skip on next iteration. skip += take; // File sequence no for split file. fileno += 1; // Filename for split file. // Create a partial xml document. XElement frag = new XElement(rootElement, c1); // Save to disk. var newStream = new MemoryStream(); frag.Save(newStream); newStream.Position = 0; pc.ResourceTracker.AddResource(newStream); IBaseMessage newmsg = pc.GetMessageFactory().CreateMessage(); newmsg.AddPart("Body", pc.GetMessageFactory().CreateMessagePart(), true); newmsg.BodyPart.Data = newStream; newmsg.Context = PipelineUtil.CloneMessageContext(inmsg.Context); //outMsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", "Namespace#Root"); var msgtype = (string.IsNullOrEmpty(rootElement.Namespace.NamespaceName)?"" : rootElement.Namespace.NamespaceName + "#") + rootElement.LocalName; newmsg.Context.Write("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype); newmsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype); _msgs.Enqueue(newmsg); } } } }
public void Push(object obj) { lock (((ICollection)queue).SyncRoot) // предохраняемся от повреждения очереди другим потоком { queue.Enqueue(obj); Console.WriteLine("push value {0}", obj); Count++; waitEvent.Set(); // оповещаем pop, что добавлен новый элемент } }
public void GetSumOfSlindingWindow(int[] arr, int windowSize) { // queue to keep track of elements of the window var queue = new System.Collections.Queue(); var sum = 0; for (var i = 0; i < windowSize; i++) { queue.Enqueue(arr[i]); sum = sum + arr[i]; } Console.Write(sum + ", "); for (var i = windowSize; i < arr.Length; i++) { var val = queue.Dequeue(); sum = sum - (int)val; queue.Enqueue(arr[i]); sum = sum + arr[i]; Console.Write(sum + ", "); } /* * if (a == null || k == 0 || a.length == 0) * return; // confirm with interviewer what to do for this case * // LinkedList implements Queue interface in Java * Queue<Integer> q = new LinkedList<>(); * int sum = 0; * for (int i = 0; i < a.length; i++) { * if (q.size() == k) { * int last = q.remove(); * sum -= last; * } * q.add(a[i]); * sum += a[i]; * if (q.size() == k) { * System.out.println(sum); * } * } */ }
public static void Add(string key, CacheItem item) { if (ItemDictionary.Count >= MaxCount || Size >= MaxSize) { Clear(); } //Monitor.Enter(ItemDictionary); _readWriteLock.EnterWriteLock(); try { if (ItemDictionary.ContainsKey(key)) { ItemDictionary[key].timestamp = DateTime.Now; ItemDictionary[key].expiryDate = item.expiryDate; ItemDictionary[key].value = item.value; } else { Scavange(); //Monitor.Enter(keyQueue); //try //{ keyQueue.Enqueue(key); //} //finally //{ // Monitor.Exit(keyQueue); //} ItemDictionary.Add(key, new CacheItem(DateTime.Now, item.value, item.expiryDate)); Size += item.value.Length; } } finally { _readWriteLock.ExitWriteLock(); //Monitor.Exit(ItemDictionary); } }
//save selections for use in mouseup private void gridControl1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { gridControl1.PointToRowCol(new Point(e.X, e.Y), out this.mouseDownRow, out this.mouseDownCol); if (mouseDownCol == colBase && gridControl1.CurrentCell.ColIndex != colBase) { //save the old selections so we can reset them later oldSelections = new Queue(); foreach (GridRangeInfo r in gridControl1.Selections.Ranges) { oldSelections.Enqueue(r); } } }
private static Hashtable GetArgumentTypesCombination(Hashtable htArgType1, Hashtable htArgType2, int indx, int argTypeNo) { Hashtable htAll = new Hashtable(); if (indx != 0) { IDictionaryEnumerator ide3 = htArgType2.GetEnumerator(); while (ide3.MoveNext()) { IDictionaryEnumerator ide2 = htArgType1.GetEnumerator(); while (ide2.MoveNext()) { System.Collections.Queue q = (System.Collections.Queue)((System.Collections.Queue)ide2.Value).Clone(); q.Enqueue(new TypeHandlePair((Type)ide3.Key, (short)ide3.Value)); htAll.Add(argTypeNo.ToString(), q); argTypeNo++; } } } else { IDictionaryEnumerator ide = htArgType1.GetEnumerator(); while (ide.MoveNext()) { IDictionaryEnumerator ide2 = htArgType2.GetEnumerator(); while (ide2.MoveNext()) { Hashtable ht3 = new Hashtable(); System.Collections.Queue q = new System.Collections.Queue(); q.Enqueue(new TypeHandlePair((Type)ide.Key, (short)ide.Value)); q.Enqueue(new TypeHandlePair((Type)ide2.Key, (short)ide2.Value)); htAll.Add(argTypeNo.ToString(), q); argTypeNo++; } } } return(htAll); }
private bool OnDataArrived(object data, IInputPort ip) { if (data != null) { m_queue.Enqueue(data); if (ObjectEnqueued != null) { ObjectEnqueued(this, data); } LevelChangedEvent(Count - 1, Count, this); m_output.NotifyDataAvailable(); } return(true); }
static public int Enqueue(IntPtr l) { try { System.Collections.Queue self = (System.Collections.Queue)checkSelf(l); System.Object a1; checkType(l, 2, out a1); self.Enqueue(a1); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
static void add_level_data_to_queue(Node root, int level) { if (root != null) { if (level == 1) { q.Enqueue(root.data); } else { add_level_data_to_queue(root.left, level - 1); add_level_data_to_queue(root.right, level - 1); } } }
static int Enqueue(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); obj.Enqueue(arg0); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
/// <summary> /// Called from RunCommandLine() tool to report the output of the currently /// executing commmand. /// </summary> /// <param name="process">Executing process.</param> /// <param name="stdin">Standard input stream.</param> /// <param name="data">Data read from the standard output or error streams.</param> private void CommandLineIOHandler(Process process, StreamWriter stdin, CommandLine.StreamData data) { if (process.HasExited || data.data == null) { return; } // Count lines in stdout. if (data.handle == 0) { linesReported += CountLines(data.text); } // Enqueue data for the text view. textQueue.Enqueue(System.Text.Encoding.UTF8.GetString(data.data)); }
private void PruneAbortedRequests() { lock (this.m_ConnectionList) { System.Collections.Queue queue = new System.Collections.Queue(); foreach (HttpWebRequest request in this.AuthenticationRequestQueue) { if (!request.Aborted) { queue.Enqueue(request); } } this.AuthenticationRequestQueue = queue; } }
/// <summary> /// Whem we start a transaction we must redeliver any rolled back messages /// </summary> public void RedeliverRolledBackMessages() { lock (semaphore) { System.Collections.Queue replacement = new System.Collections.Queue(queue.Count + messagesToRedeliver.Count); foreach (Apache.NMS.IMessage element in messagesToRedeliver) { replacement.Enqueue(element); } messagesToRedeliver.Clear(); while (queue.Count > 0) { Apache.NMS.IMessage element = (Apache.NMS.IMessage)queue.Dequeue(); replacement.Enqueue(element); } queue = replacement; if (queue.Count > 0) { messageReceivedEventHandle.Set(); } } }
/// <summary> /// Called from RunCommandLine() tool to report the output of the currently /// executing commmand. /// </summary> /// <param name="process">Executing process.</param> /// <param name="stdin">Standard input stream.</param> /// <param name="data">Data read from the standard output or error streams.</param> private void CommandLineIOHandler(Process process, StreamWriter stdin, CommandLine.StreamData data) { // Note: ignoring process.HasExited to print errors that were emitted during shutdown. if (data.data == null) { return; } // Count lines in stdout. if (data.handle == 0) { linesReported += CountLines(data.text); } // Enqueue data for the text view. textQueue.Enqueue(System.Text.Encoding.UTF8.GetString(data.data)); }
/// <summary> /// Trigger the Client. /// </summary> /// <param name="actorName">Destination Actor Name.</param> /// <param name="trigger">Trigger message.</param> /// <param name="awaitCompletion">Boolean indicating whether this a synchronous call or not.</param> /// <returns>Boolean indicating success or failure.</returns> public bool TriggerClient(ActorName actorName, BaseTrigger trigger, bool awaitCompletion) { _awaitCompletion = awaitCompletion; Hl7Trigger hl7Trigger = (Hl7Trigger)trigger; _triggerQueue.Enqueue(hl7Trigger); // Check if this is a synchronous call or not if (_awaitCompletion == true) { // Timeout of 0 means "no timeout". _semaphore.Wait(0); } return(true); }
public void AddPoint() { Quaternion q1 = new Quaternion(-vectDiagonal.X, -vectDiagonal.Y, -vectDiagonal.Z, 0); q1 = (Quaternion.Conjugate(quat) * q1) * quat; while (points.Count >= psize) { points.Dequeue(); } points.Enqueue(new Vector3(q1.X, q1.Y, q1.Z)); Quaternion q = new Quaternion(-Center.X, -Center.Y, -Center.Z, 0); q = (Quaternion.Conjugate(quat) * q) * quat; PotentialEnergy = (q.Y) * Mass * gravitation; // mgh centrum masy KineticEnergyW = Vector3.Dot(mulv(ref InertiaTensor, omega), omega) / 2; // mv^2/2 + Iw^2 / 2 + energia kinetyczna // 0.5f*(Mass/gravitation) * Vector3.Dot(omega,omega) }
private void CreateOutgoingMessage(IPipelineContext pContext, String messageString, string namespaceURI, string rootElement) { IBaseMessage outMsg; try { //create outgoing message outMsg = pContext.GetMessageFactory().CreateMessage(); outMsg.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true); outMsg.Context.Promote("MessageType", systemPropertiesNamespace, namespaceURI + "#" + rootElement.Replace("ns0:", "")); byte[] bufferOoutgoingMessage = System.Text.ASCIIEncoding.ASCII.GetBytes(messageString); outMsg.BodyPart.Data = new MemoryStream(bufferOoutgoingMessage); qOutputMsgs.Enqueue(outMsg); } catch (Exception ex) { throw new ApplicationException("Error in queueing outgoing messages: " + ex.Message); } }
private void CreateOutgoingMessage(IPipelineContext pContext, String messageString, IBaseMessage pInMsg) { IBaseMessage outMsg; try { //create outgoing message outMsg = pContext.GetMessageFactory().CreateMessage(); outMsg.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true); byte[] bufferOoutgoingMessage = System.Text.ASCIIEncoding.ASCII.GetBytes(messageString); outMsg.BodyPart.Data = new MemoryStream(bufferOoutgoingMessage); outMsg.Context = PipelineUtil.CloneMessageContext(pInMsg.Context); qOutputMsgs.Enqueue(outMsg); } catch (Exception ex) { throw new ApplicationException("Error in queueing outgoing messages: " + ex.Message); } }
void CopyItems() { Collections.NgbhItems selitems = SelectedNgbhItems; if (selitems.Count > 0) { this.Cursor = Cursors.WaitCursor; try { clipboard.Clear(); foreach (NgbhItem item in selitems) { clipboard.Enqueue(item); } } catch (Exception exception1) { this.Cursor = Cursors.Default; Helper.ExceptionMessage(Localization.Manager.GetString("errconvert"), exception1); } this.Cursor = Cursors.Default; } }
/// <summary> /// Called from RunCommandLine() tool to report the output of the currently /// executing commmand. /// </summary> /// <param name="process">Executing process.</param> /// <param name="stdin">Standard input stream.</param> /// <param name="data">Data read from the standard output or error streams.</param> private void CommandLineIOHandler(Process process, StreamWriter stdin, CommandLine.StreamData data) { if (process.HasExited || data.data == null) { return; } // Count lines in stdout. if (data.handle == 0) { linesReported += CountLines(data.text); } // Enqueue data for the text view. var newLines = System.Text.Encoding.UTF8.GetString(data.data); textQueue.Enqueue(newLines); // Write to the logger. foreach (var line in CommandLine.SplitLines(newLines)) { logger.Log(line, level: LogLevel.Verbose); } }
/// <summary> /// SelectionMarker sample Customizations /// </summary> private void SampleCustomization() { gridControl1.CommandStack.Enabled = true; gridControl1.CommandStack.UndoStack.Clear(); gridControl1.ThemesEnabled = true; gridControl1.Selections.Add(GridRangeInfo.Cells(12, 3, 14, 7)); gridControl1.CurrentCell.MoveTo(12, 3); oldSelections = new Queue(); oldSelections.Enqueue(GridRangeInfo.Cells(12, 3, 14, 7)); this.gridControl1.GridVisualStyles = Syncfusion.Windows.Forms.GridVisualStyles.Metro; this.gridControl1.DefaultGridBorderStyle = GridBorderStyle.Solid; this.gridControl1.BackColor = Color.White; this.gridControl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; GridStyleInfo style = gridControl1.BaseStylesMap["Header"].StyleInfo; style.Font.Facename = "Segoe UI"; this.StartPosition = FormStartPosition.CenterScreen; this.ResumeLayout(); }