Wednesday, February 28, 2007 11:09 AM bart

C# 2.0 iterators revisited - The Pascal triangle

Last week, I introduced C# 2.0 to a few academic people who had prior exposure to C, C++ and Java. Does language matter is an often heard question. Well, in the world of .NET, the importance of language choice has somewhat blurred but richness of languages still is a great decision factor, certainly for general-purpose languages.

Typical samples of developer convenience in the world of C# include the foreach loop, nullable types, generics, etc. One more dark feature is the principle of iterators and lazyness however; the typical example of an even number generator and the explanation of a finate state automaton isn't the best approach to introduce this feature...

So, I came up with another (more academic) sample: the Pascal triangle. For those who're not familiar with this concept, it looks as follows:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

Basically, each number inside the triangle (i.e. without the borders that always contain 1) is the sum of the two numbers above it. And yes, it has its use (beside of a geeky wallpaper layout for math freaks): every row indicates the coefficients of the mixed products of a and b when calculating (a+b)^n (Binomium of Newton).

So, here's the code:

1 using System; 2 using System.Collections.Generic; 3 4 class Pascal 5 { 6 static void Main() 7 { 8 foreach (uint[] row in GetPascalTriangle()) 9 { 10 Print(row); 11 Console.ReadKey(); 12 } 13 } 14 15 static void Print(uint[] row) 16 { 17 foreach (uint e in row) 18 Console.Write("{0}\t", e); 19 Console.WriteLine(); 20 } 21 22 static IEnumerable<uint[]> GetPascalTriangle() 23 { 24 uint[] row = new uint[1] { 1 }; 25 26 for(int n = 2; ; n++) 27 { 28 yield return row; 29 30 uint[] nrow = new uint[n]; 31 Array.Copy(row, nrow, n-1); 32 for (int i = 1; i < n; i++) 33 nrow[i] += row[i-1]; 34 row = nrow; 35 } 36 } 37 }

The code above produces something like this:

If you want to know how iterators work, check out my former post on C# 2.0 Iterators.

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# re: C# 2.0 iterators revisited - The Pascal triangle

Sunday, March 04, 2007 1:27 PM by Jason Whittington

Nice example.  A lot of good CS problems are nicely expresses this way.In my classes I've done:

* the Fibonacci sequence,

* an inorder traveral of a binary tree,

* Tower of Hanoi

* Knight's tour

* Taylor series approximations for sin(x), cos(x)

# ?????????????????? ?????????????????? ?? ?????????????????????? ?????????????? ???? C#&#8230; &laquo; ???????? ???????????? ??????????????

Pingback from  ?????????????????? ?????????????????? ?? ?????????????????????? ?????????????? ???? C#&#8230; &laquo; ???????? ???????????? ??????????????