Archive for May, 2012

Pascal’s triangle and C#’s answer to typedef

Posted in Coding with tags , on 2012.05.31 by kasewick

The C language and its close relatives have a typedef statement to create an alias to a type. The closest thing that the C# language has is a variation of the using statement as shown below. The scope is never more than the source file so its usefulness is very limited.

This program creates and outputs Pascal’s triangle to as many rows as possible without overflowing the type specified by WNum – in this example it is a Byte.

using System;
using System.Collections.Generic;

namespace Pascals
{
    using WNum = System.Byte;

    class Program
    {
        static void Main ()
        {
            var pt = new List<WNum[]> ();

            // Generate the triangle
            pt.Add (new WNum[] { 1 });
            try
            {
                for (int n = 1; ; ++n)
                {
                    var row = new WNum[n+1];
                    row[0] = 1;
                    for (int k = 1; k <= n - 1; ++k)
                        row[k] = checked ((WNum) (pt[n-1][k-1]
                                                + pt[n-1][k]));
                    row[n] = 1;
                    pt.Add (row);
                }
            }
            catch (OverflowException) { }

            // Output the triangle
            for (int n = 0; n < pt.Count; ++n)
                for (int k = 0; ; ++k)
                {
                    Console.Write (pt[n][k]);
                    if (k == n)
                    {
                        Console.WriteLine(); break;
                    }
                    Console.Write (" ");
                }
        }
    }
}

For Byte, this will create rows 0 to 10 and output them:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1

The maximum rows for other types are:

System type Max. row
Int32 34
UInt32 35
Int64 67
UInt64 68

Element retrieval of Pascal’s triangle is useful in fields such as combinatorics. While algorithms exist to calculate elements without building the entire table, they are slower (once the table is built) than a simple array lookup and will overflow well before the limits listed above.