//---------------------------------------------------------------------------- // Copyright (C) 2013-2015 Fabrice HARROUET (ENIB) // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. // The author makes no representations about the suitability of this // software for any purpose. // It is provided "as is" without express or implied warranty. //---------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; public class MyRange : IEnumerable { protected int _begin,_end; public MyRange(int begin, int end) { _begin=begin; _end=end; } public IEnumerator GetEnumerator() { for(int i=_begin;i<_end;++i) { yield return i; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class Node { public T value; public Node left; public Node right; public Node(T value) { this.value=value; this.left=null; this.right=null; } public IEnumerable> dfWalk() { yield return this; if(left!=null) foreach(Node n in left.dfWalk()) yield return n; if(right!=null) foreach(Node n in right.dfWalk()) yield return n; } public IEnumerable> bfWalk() { Queue> q=new Queue>(); q.Enqueue(this); while(q.Count!=0) { Node n=q.Dequeue(); yield return n; if(n.left!=null) q.Enqueue(n.left); if(n.right!=null) q.Enqueue(n.right); } } } public class Test { public static IEnumerable range(int begin, int end) { for(int i=begin;i dummyPrime() { for(int i=2;;++i) { bool prime=true; for(int j=2;j makeTree(int left, int right) { int mid=(left+right)/2; Node n=new Node(mid); if(mid>left) n.left=makeTree(left,mid-1); if(mid r1=new MyRange(0,3); foreach(int i in r1) { foreach(int j in r1) { Console.Write("{0};{1} ",i,j); } Console.WriteLine(""); } Console.WriteLine("~~~ with enumerable ~~~~"); IEnumerable r2=range(0,3); foreach(int i in r2) { foreach(int j in r2) { Console.Write("{0};{1} ",i,j); } Console.WriteLine(""); } Console.WriteLine("~~~ dummy prime ~~~~"); int lastHundred=0; foreach(int p in dummyPrime()) { if(p/100!=lastHundred) { Console.Write("\n"); lastHundred=p/100; } Console.Write("{0} ",p); if(p>1000) break; } Console.Write("\n"); Console.WriteLine("~~~ depth first tree walk ~~~~"); Node root=makeTree(0,31); foreach(Node n in root.dfWalk()) { Console.WriteLine("{0} {1}",new String('*',n.value),n.value); } Console.WriteLine("~~~ breadth first tree walk ~~~~"); foreach(Node n in root.bfWalk()) { Console.WriteLine("{0} {1}",new String('*',n.value),n.value); } } } //----------------------------------------------------------------------------