Sunday, December 21, 2008

C# - Counting the number of occurrences of a substring

How many times have you needed to find the total number of times a substring has appeared within a string? This common programming problem can be approached from many different angles.

You could write brute force code that walks through the string and looks at it character by character, keeping a tally of how many complete matches with the substring was found.

You could use IndexOf within a while loop, incrementing the counter and moving the start point on each iteration of the loop, exiting the loop when IndexOf returns that there are no more occurrences of the substring.

But, there is only one way that I know how to do it without a loop. Use the Replace method of string.

Here is a code snippet showing how to use this very simple yet powerful way to count the number of occurrences of a substring within a string.


string myString = "Lorem ipsum dolor sit amet, " +
"consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna " +
"aliqua. Ut enim ad minim veniam, quis nostrud " +
"exercitation ullamco laboris nisi ut aliquip " +
"ex ea commodo consequat. Duis aute irure " +
"dolor in reprehenderit in voluptate velit " +
"esse cillum dolore eu fugiat nulla pariatur. " +
"Excepteur sint occaecat cupidatat non proident, " +
"sunt in culpa qui officia deserunt mollit anim " +
"id est laborum.";

string mySubString = "dolor";

int Count = (myString.Length -
myString.Replace(mySubString, string.Empty).Length)
/ mySubString.Length;


This will return a count of 4, the correct number without a single loop in your code!

This code is case sensitive. To create a case insensitive version, just move myString and mySubString to lowercase.


string mySubString = "lo";

int Count = (myString.Length -
myString.ToLower().Replace(mySubString.ToLower(),
string.Empty).Length) / mySubString.Length;


The case sensitive version would have only returned 4 because it would not have found the first lo at the beginning because the L in Lorem is capitalized. But with the case insensitive version, the code correctly finds all 5 instances of our substring.

This may seem like such a small thing, but everyday programming is filled with these "Old School" tricks!

Sunday, December 14, 2008

C# - Hiding interface methods (How and Why)

In my attempt to create a "Generic Object Reference Implementation" (I talked about this in a previous post here) version of System.Collections.Generic.LinkedList I needed to implement the ICollection<T> interface.

Well, you will notice that the Frameworks' LinkedList implementation has four methods to add a node: AddFirst, AddBefore, AddAfter and AddLast. Yet, ICollection<T> demands that we have another method called Add.

But, LinkedList does not have and Add method.

And, LinkedList does implement the ICollection<T> interface.

Hmmm.

Well, after some searching and a Usenet post, I found out how it is done.

It is called Implementing the interface method EXPLICITLY for the interface. This is accomplished by placing the name of the interface before the method name, as such:

ICollection<T>.Add

The method Add will now will be only available when the class is cast as ICollection<T>. This gives us the best of both worlds, we get the benefit of implementing ICollection<T> without having to expose a method that may not make sense in the context of the class.

Saturday, December 6, 2008

Switcheroo - An old "Magazine" game in Silverlight, Part 1

In a previous post, I described the game Switcheroo. In this first post we will create a the start splash screen, the game board and the end splash screen.

The splash screen for a very visual game should be striking. Unfortunately, I am not a graphic artist, so the best I could come up with is the name switcheroo rendered using WordArt in Word.

We need to display the splash screen along with a start button. When the start button is clicked, we can then hide the splash screen and display the game board.

If you remember from that previous post, players can either place a piece on the 5x5 gameboard or rotate a row to the left or right, or rotate a column up or down. So, not only do we need a 5x5 checkerboard but we also need a mechanism to allow the players to rotate the columns and rows.

To accomplish this I added an extra column at the start and the end of the gameboard and an extra row to the top and the bottom of the gameboard. I added small golden arrows.

Once the game has been one or lost, on the placement of the winning move, we need to hide the gameboard and show the splash screen again. This time with a button declaring their win or loss and asking if they wish to play again.

The only problem with this is from a aesthetic point. When we place the winning piece, rotate the winning piece into place or our opponents move defeats us, we do not want to immediately flash to the splash page. The player may not have been able to even see that the move was a winning move or what their opponent even did to win, so we need to include a delay upon determining that the game is in fact over.

In the code for this first part, the both splash screens will work as they are supposed to, but since we have not created any game logic yet, we will consider any click on the gameboard to be the winning move and after our short delay the "You lose" version of the splash screen will display.

If you click on the button, the gameboard will display again and the whole process will start again, but the code will rotate between the "You win" and "You lose" messages to verify that both code paths work.

As you can see, instead of a lot of repetitive XAML, the only hardcoded XAML sets up the grid that will contain the gameboard and the elements for the splash screen.
<UserControl x:Class="Switcheroo.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="300">
<Grid x:Name="LayoutRoot"
Tag="Bob">
<Grid.ColumnDefinitions>
<ColumnDefinition Width='25' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='25' />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='25' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='25' />
</Grid.RowDefinitions>
<Image x:Name="XamlBoard"
Grid.RowSpan='7'
Grid.ColumnSpan='7'
Source='Splash.png' />
<StackPanel VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.RowSpan="7"
Grid.ColumnSpan="7">
<Button Click="Start_Click"
Content="Start"></Button>
</StackPanel>
</Grid>
</UserControl>

The XAML code also available here!

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Switcheroo
{
public partial class Page
{
private class MyColors
{
public static Color Aliceblue { get { return GenerateColorStruct(0xFFF0F8FF); } }
public static Color Cyan { get { return GenerateColorStruct(0xFF00FFFF); } }
public static Color Darkcyan { get { return GenerateColorStruct(0xFF008B8B); } }
public static Color Darkgoldenrod { get { return GenerateColorStruct(0xFFB8860B); } }
public static Color Gold { get { return GenerateColorStruct(0xFFFFD700); } }

private static Color GenerateColorStruct(uint color)
{
var mask = 0x000000FF;

var returnval = new Color
{
A = ((byte)((color >> 24) & mask)),
R = ((byte)((color >> 16) & mask)),
G = ((byte)((color >> 8) & mask)),
B = ((byte)((color) & mask))
};

return returnval;
}
}

private class GameBoard
{
internal readonly int[,] Board = new int[5, 5];

public GameBoard()
{
for (var i = 0; i < 5; i++)
{
for (var j = 0; j < 5; j++)
{
Board[i, j] = -1;
}
}
}
}

readonly DispatcherTimer dt = new DispatcherTimer();

private bool GameOver;
private int GameWinner = -1;
private GameBoard Switcheroo = new GameBoard();

public Page()
{
InitializeComponent();
}

private void Start_Click(object sender, RoutedEventArgs e)
{
Switcheroo = new GameBoard();
LayoutRoot.Children.Clear();
CreateGameBoard();
GameOver = false;
}

private void dt_Tick(object sender, EventArgs e)
{
dt.Stop();
DisplayGameOverSplash();
}

private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
GameOver = true;

GameWinner = GameWinner == 0 ? 1 : 0;

if (GameOver)
{
dt.Interval = new TimeSpan(0, 0, 0, 0, 500); // 500 Milliseconds
dt.Tick += dt_Tick;
dt.Start();
}
}

private void CreateGameBoard()
{
var CellColor = false;
Canvas c;

for (var i = 0; i < 7; i++)
{
for (var j = 0; j < 7; j++)
{
if (i != 0 && i != 6 && j != 0 && j != 6)
{
c = new Canvas
{
Tag = (i + ":" + j),
Background =
(CellColor
? new SolidColorBrush(MyColors.Aliceblue)
: new SolidColorBrush(MyColors.Darkcyan))
};
}
else
{
c = new Canvas
{
Tag = (i + ":" + j),
Background = new SolidColorBrush(MyColors.Cyan)
};


if (j == 6 && i != 0 && i != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(10, 5));
p.Points.Add(new Point(40, 5));
p.Points.Add(new Point(25, 15));

c.Children.Add(p);
}
else if (j == 0 && i != 0 && i != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(10, 20));
p.Points.Add(new Point(40, 20));
p.Points.Add(new Point(25, 10));

c.Children.Add(p);

}
else if (i == 6 && j != 0 && j != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(5, 10));
p.Points.Add(new Point(5, 40));
p.Points.Add(new Point(15, 25));

c.Children.Add(p);

}
else if (i == 0 && j != 0 && j != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(20, 10));
p.Points.Add(new Point(20, 40));
p.Points.Add(new Point(10, 25));

c.Children.Add(p);

}
}

c.MouseLeftButtonDown += Canvas_MouseLeftButtonDown;
Grid.SetColumn(c, i);
Grid.SetRow(c, j);

LayoutRoot.Children.Add(c);

CellColor = !CellColor;
}
}
}

private void DisplayGameOverSplash()
{
string ButtonText = GameWinner != 0 ? "You Win! Play Again?" : "You Loose! Play Again?";

const string Splash = "<Image xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " +
"x:Name='XamlBoard' Grid.RowSpan='7' Grid.ColumnSpan='7' Source='Splash.png' /> ";

const string Stack = "<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' VerticalAlignment='Center' " +
"HorizontalAlignment='Center' Grid.RowSpan='7' Grid.ColumnSpan='7' />";

string Button = "<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Content='" + ButtonText + "'></Button>";

LayoutRoot.Children.Clear();
LayoutRoot.Children.Add((Image)XamlReader.Load(Splash));
LayoutRoot.Children.Add((StackPanel)XamlReader.Load(Stack));
((StackPanel)LayoutRoot.Children[1]).Children.Add((Button)XamlReader.Load(Button));
((Button)((StackPanel)LayoutRoot.Children[1]).Children[0]).Click += Start_Click;
}
}
}

The C# code also available here!

Monday, December 1, 2008

C# latin squares or shuffling a 2D array

Another problem in "Problems for Computer Solution" by Fred Gruenberger and George Jaffray concerns Latin Squares. Latin Squares are essentially two dimensional array that is shuffled in both dimensions.

I believe an example is now in order:

If you start with a set of numbers:
    1,2,3
Then shuffle them:
    3,1,2
You then have an array shuffled in a single dimension, but if you have a two dimensional array where your set of numbers:
    1,2,3
is repeated for each row:
    1,2,3
    1,2,3
    1,2,3

A possible suffling of this two dimensional array could look like this:
    3,1,2
    1,2,3
    2,3,1

The numbers are now shuffled so that each row and column is different from every other row and column and - here is the most important part - no member of the set is repeated in a row or column.

One possible way to progammatically generate a Latin Square is to use this trick - Use the first row not only as data but as the rule on how to place the values for all the rest of the rows.

I believe another example is now in order:

If you start with our shuffled set of numbers:
    3,1,2

Now look at the data and say:
In the first row the 2 is in the 3rd column.
In the second row the 2 is in the 1st column.
In the third row the 2 is in the 2nd column.

3rd column, 1st column, 2nd column - thats our first row! 3,1,2!

Now rotate the first row by taking the first value and placing at the end - 1,2,3 - and do the same thing to the original data. So, lets look at the data and say:
In the first row the 3 is in the 1st column.
In the second row the 3 is in the 2nd column.
In the third row the 3 is in the 3rd column.

Rotate one last time - 2,3,1 - and do the same thing to the original data. So, lets look at the data and say one last time:
In the first row the 1 is in the 2nd column.
In the second row the 1 is in the 3rd column.
In the third row the 1 is in the 1st column.

So using the rules above we generated:
    3,1,2
    2,3,1
    1,2,3

Here is a 9x9 array shuffled using the above trick:
    3,2,6,5,9,4,1,7,8
    5,6,7,8,4,2,3,1,9
    8,7,1,9,2,6,5,3,4
    9,1,3,4,6,7,8,5,2
    4,3,5,2,7,1,9,8,6
    2,5,8,6,1,3,4,9,7
    6,8,9,7,3,5,2,4,1
    7,9,4,1,5,8,6,2,3
    1,4,2,3,8,9,7,6,5

And, here is the code that can generate Latin Squares using the above trick:


using System;
using System.Collections;

class LatinSquare
{
static void Main()
{
var LatinSquare = new int[9, 9];
var Pattern = new int[] {1,2,3,4,5,6,7,8,9};

Pattern = Shuffle(Pattern);

//Use the first row as a pattern for the rest
//of the Latin Square
for (int i = 0; i < 9; i++)
{
{LatinSquare[i,0] = Pattern[i];
}

for (int x = 0; x < 9; x++)
{
for (int y = 1; y < 9; y++)
{
LatinSquare[Pattern[y] - 1, y] =
LatinSquare[LatinSquare[x, 0] - 1, 0];
}

Pattern = RotatePattern(Pattern);
}

PrintLatinSquare(LatinSquare);

Console.Read();
}

private static T[] Shuffle(T[] OriginalArray)
{
var matrix = new SortedList();
var r = new Random();

for (int x = 0; x <= OriginalArray.GetUpperBound(0); x++)
{
int i = r.Next();

if (!matrix.ContainsKey(i))
{
matrix.Add(i, OriginalArray[x]);
}
}

var OutputArray = new T[OriginalArray.Length];

var counter = 0;
foreach (DictionaryEntry entry in matrix)
{
OutputArray[counter++] = (T)entry.Value;
}

return OutputArray;
}

private static int[] RotatePattern(int[] Pattern)
{
int temp = Pattern[0];

;for (int y = 0; y < 9 - 1; y++)
{
Pattern[y] = Pattern[y + 1];
}

Pattern[9 - 1] = temp;

return Pattern;
}

private static void PrintLatinSquare(int[,] LatinSquare)
{
//Print out the Latin Square
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Console.Write(LatinSquare[j, i].ToString().PadLeft(3));
}
Console.WriteLine();
}
}
}


The code also available here!

Monday, November 24, 2008

Dr. Dobb's Journal CD, for the really nerdy "Old School" Dot Netters

I remember way back when I was just starting my computer science education. I would get the latest edition of Dr. Dobb's Journal, first at the news stand then later in the mail, and I would read it from cover to cover. Not that I understood a lot of what I was reading, but I realized that this was information that I would someday need to know.

My freshman level language was Pascal and I had not gotten to learning about pointers yet. Even though the published source code was in C, just reading the descriptions of the various algorithms that Dr. Dobb's Journal published helped my understanding of how complex data structures were built.

As I went from Computer Science class to Computer Science class I kept using my back issues as reference material. In a way, Dr. Dobb's Journal was, for me, the equivalent of Computer Science version of Scientific American. Well, like they say, three moves is the same as a fire, and I've moved may more times than three, so I have no idea where all my old DDJ's are or if I even still own them.

One day though, I got a letter asking me to re-subscribe, with the offer of all the issues from January 1988 through December 2000 on CD. Well that was just too good to pass up! I re-subscribed, got my CD and stashed it away.

Well, when Dot Net came out it had all those nifty System.Collection classes. Without any work I had a Stack, a Queue, a Hashtable and an ArrayList that was kinda like a cross between a linked list and an array. What need did I have for any of those "roll your own" abstract data types?

Live and learn I guess, but not all Stacks, etc, are built alike. The Dot Net version is array based. Now, I'm not saying that that is bad, just that it is not pointer (or Object Reference) based so it has different characteristics. Plus, where is my binary tree or red-black tree or skip list? How about a nice graph?

Well, out comes the CD. A quick search and I've got a nice bit of source code to start a C# version of a skip list.

Truth be told, for a complete toolbox for Dot Net and C# specifically, the System.Collection namespace should contain abstract data types based on (When Possible):

  • An Object based Array Implementation
  • A Generic Array Implementation
  • A Object based Object Reference Implementation
  • A Generic Object Reference Implementation
  • A Object based Pointer (unsafe) Implementation
  • A Generic Pointer (unsafe) Implementation

    Since they all have different performance, security and memory concerns.

    Maybe, someday, with the help of my trusty DDJ CD I'll even get around to coding all those ADT's!
  • Monday, November 17, 2008

    Shuffling arrays in C#

    Have you ever had a need to output some array of objects in a random order? Say a array of strings ... with 52 elements that each represent a playing card?

    Well, if you have ever had a need to shuffle the elements in an array, you have probably found that there are only a few different algorithms: Either card swapping or assigning a random Key to each element and then sorting by the key.

    Unfortunately there are quite a few issues involved with the swap shuffle so I wanted a to use the sort version. Well, what has tuples? Hashtables? Hashtables! So, how do you sort a Hashtable? Hmmmm, maybe I need to think harder about this.

    Hey, did everyone realize their is a sorted version called a SortedList?

    OK, So we will use the SortedList. Now I want this function to use Generics so that it will take an array of any type. So lets try!

    (Mind you that this is not nearly as small as the implementation here but I am not posting here to show how to shuffle in the least number of lines or use the latest technology, but with an eye towards the most understandable source.)

    private static T[] Shuffle <T> (T[] OriginalArray)
    {
    var matrix = new SortedList();
    var r = new Random();

    for (var x = 0; x <= OriginalArray.GetUpperBound(0); x++)
    {
    var i = r.Next();

    while (matrix.ContainsKey(i)) { i = r.Next(); }

    matrix.Add(i, OriginalArray[x]);
    }

    var OutputArray = new T[OriginalArray.Length];

    matrix.Values.CopyTo(OutputArray, 0);

    return OutputArray;
    }

    Tuesday, November 11, 2008

    Dynamically adding XAML strings from C#

    In designing the screen for my silverlight game Switcheroo, I wanted to be able to dynamically add XAML chunks that represent the pieces (Ellipse). True, I could have just created the graphic elements property by property, but since the only difference between all the game pieces is if they are black or red, I thought that if it only took one or two lines of code, it would be a more elegant solution.

    I wanted to separate the internal representation of the gameboard in the gaming object from the XAML front end. Then I could just clear the gameboard and recreate all the pieces after the gameboard object was updated. The question was, how?

    Well I googled high and low but though I found many "solutions" to my problem, none of them worked. After trying different combinations of the aforementioned solutions, I got closer. This is my first try that made any headway:

    const string red =
    "<Ellipse Stroke='Black' Fill='Red' Height='30' Width='30' Margin='10,10,10,10' />";

    LayoutRoot.Children.Add((Ellipse)XamlReader.Load(red));


    But the error I got back was:

    AG_E_PARSER_MISSING_DEFAULT_NAMESPACE [Line: 0 Position: 0]

    Not a very helpful error message! Well, googling this error I found others that were getting the same error and a simple answer - the element must contain the same namespace. The only namespace is the one at the beginning of the XAML document thought. Well, I thought, it's worth a shot. So I added the namespace lines from the beginning of the element. Our code now looked like this:

    const string red =
    "<Ellipse xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Stroke='Black' Fill='Red' Height='30' Width='30' Margin='10,10,10,10' />";

    LayoutRoot.Children.Add((Ellipse)XamlReader.Load(red));


    And low and behold! It worked!

    So when you have lots of repetitious XAML or elements like named colors that cannot be easily replicated in code, just use the XAML string!

    Monday, October 27, 2008

    Zeller's Congruence in C#

    In "Problems for Computer Solution" by Fred Gruenberger and George Jaffray, one of the problems revolved around determining what day of the week for any date. The algorithm is called Zeller's Congruence.

    In this day and age, where finding the day of the week is as simple as DateTime.Now.DayOfWeek programmers may not realize that in the early days of computing it was much more difficult. One way was to code an implementation of Zeller's Congruence. Towards the end of the 19th century, Christian Zeller formulated an algorithm that could calculate the day of the week.

    Back in the 60's, second year computer science students used the problem of implementing this algorithm as a semester project. Yet, now even if we do not use the .Net Framework, implementing the algorithm is the work of a few minutes.

    The Algorithm:

    D = Day of the month
    M = Month (With a trick, March is the first month of the year, January and February then being the 11th and 12th month of the previous year)
    X = Decade (With a trick - see Month above)
    C = Century (With a trick - see Month above)

    (int(2.6 * M - 0.2) + D + X + int(X / 4) + int(C / 4) - (2 - C)) modulo 7

    One cool trick in the code below is calculating the the month of the year (Including the trick above) using only a math, no logic.

    Here it is step by step:

    Start with the months as numbers: 1,2,3 ... 11,12
    Add 9 to each month: 10,11,12 ... 20,21
    Modulo each month by 12 (%): 10,11,0 ... 8,9
    Add 1: 11,12,1 ... 9,10

    So now we have what we wanted, Jan = 11, Feb = 12, Mar = 1 ... Nov = 9, Dec = 10

    Here is the full algorithm:

    string[] DaysOfTheWeek =
        {"Sunday", "Monday", "Tuesday",
        "Wednesday", "Thursday", "Friday", "Saturday"};

    int Day = DateTime.Now.Day;
    int Month = ((DateTime.Now.Month + 9) % 12) + 1;

    int YearsInCentury = Month > 10 ?
        (DateTime.Now.Year - 1) % 100 :
        DateTime.Now.Year % 100;

    int Century = YearsInCentury == 99 && Month > 10 ?
        (DateTime.Now.Year - 100) / 100 :
        DateTime.Now.Year / 100;

    int DayOfWeek = ((((int)((2.6 * (float)Month) - 0.2)
        + Day + YearsInCentury + (YearsInCentury / 4)
        + (Century / 4) - (2 * Century))) % 7);

    Console.Write(DaysOfTheWeek[DayOfWeek]);
    Console.Read();

    Sunday, October 26, 2008

    LINQ to the rescue!

    If you have ever had multiple data sources that you pull into DataTables, you know that you can use the .Merge function to combine the data. But, what if there are dupicates? What about sorting the merged data?

    Well, using LINQ to data, you can use the power of LINQ without needing SQL Server or a database at all, for that matter. Here is a simple example using LINQ to data, to sort and pull only distinct records in the merged DataTable.

    static void Main()
    {
        var dtFirst = new DataTable();
        var dtSecond = new DataTable();

        dtFirst.Columns.Add("Value", Type.GetType("System.Int32"));
        dtSecond.Columns.Add("Value", Type.GetType("System.Int32"));

        var row = new object[1];

        for (var i = 25; i >= 0; i--)
        {
            row[0] = i;
            dtFirst.Rows.Add(row);
            row[0] = i+5;
            dtSecond.Rows.Add(row);
        }

        dtFirst.Merge(dtSecond);

        IEnumerable MyTable = dtFirst.AsEnumerable();

        var dtLinqData = (from
                MyRow
            in
                MyTable
            orderby
                MyRow.Field("Value")
            ascending
            select
                MyRow.Field("Value")).Distinct().ToArray();

        Console.WriteLine("Original Data");

        foreach (DataRow dr in dtFirst.Rows)
            Console.Write(dr["Value"] + " ");

        Console.WriteLine();
        Console.WriteLine("Linq Data");

        foreach (var dr in dtLinqData)
            Console.Write(dr + " ");

        Console.Read();

    }

    Thursday, October 23, 2008

    Where have all the colors gone?

    If you are programming in Silverlight, you probably have seen all the colors available in the XAML. Want a line that is AliceBlue, no problem, but if you want to create the same line programatically in C#, good luck.

    The Colors class is just a small subset of all the HTML named colors, so the only way to add AliceBlue is to use Color.FromArgb, so you go out to a website that lists all the colors' RGB values. AliceBlue is #F0F8FF, so you paste the RGB value into Color.FromArgb.

    But wait! Color.FromArgb expects 4 bytes, not a single number (The first byte is the Alpha value - i.e. the transparentcy of the color, hence the A in front of the RGB) and our color is only 3 bytes. We can add #FF in front of #F0F8FF but Color.FromArgb expects them to be separate values separated by a comma.

    Color.FromArgb(#FF, #F0, #F8, #FF) will not work because C# does not recognize them as numbers. The key to having C# recognize them as hex numbers is to replace the hash(#) with 0x. So AliceBlue is now Color.FromArgb(0xFF, 0xF0, 0xF8, 0xFF).

    Too much work you say? I agree. I just want to use my named colors. So, I created my own Color class that in Silverlight will output named colors!

    The code looks like this:


    private class MyColors
    {
        public static Color Aliceblue
        {
            get
            {
                return GenerateColorStruct(0xFFF0F8FF);
            }
        }

        .
        .
        .

        private static Color GenerateColorStruct
                                        (uint color)
        {
            var mask = 0x000000FF;
            var returnval = new Color
            {
                A = ((byte)((color >> 24) & mask)),
                R = ((byte)((color >> 16) & mask)),
                G = ((byte)((color >> 8) & mask)),
                B = ((byte)((color) & mask))
            };

            return returnval;
        }
    }


    The entire .cs file can be found here. Since this is a private class that you can add to any Silverlight page.cs file that needs named colors , you can also add your own named colors that you want to use all the time!

    You can also compile it to its own dll, but I like it better in the page.cs file. For size of outputs sake, right before you publish you can remove all the unused colors.

    Wednesday, October 22, 2008

    Old Games In Silverlight

    It continually amazes me how many great games were published in the 80's and 90's in hobby programming magazines. Sure, they are not the type of games that a company like Electronic Arts would be interested in and are definitely not up to the standards of today's games on the PC, but casual gaming on the web and mobile devices has possibly created a new home for these games.

    In one of my old programming magazines (Compute's! Gazette, June 1986 - Issue 36, Vol. 4, No. 6) described a game called Switcheroo, by Kevin Mykytyn and Mark Tuttle. A simple connect 5 on a 5x5 grid (horizontally or vertically, no diagonals) with a twist. The player can place a piece of his color on an empty space or he may shift a column up or down, or shift a row left or right. Any pieces that are removed from the board by the shift are places in at the end of the column or row in the newly vacant space.

    I think that this game would be a great coding test for Silverlight, so I will be posting a multi-part blog entry on writing Switcheroo in Silverlight2.0.

    Unfortunately, all the games published in Compute's! Gazette were in a version of Machine Language called "MLX", so the effort would be heroic to try to adjust the code to a more modern platform such as Silverlight. And, with the fact that there was no AI (It was a 2 player game) and we will want to play against the computer, we will be starting from scratch.

    Sunday, October 19, 2008

    Permutations

    In "Problems for Computer Solution" by Fred Gruenberger and George Jaffray, permutation was a topic for one of the problems.

    Now everyone that has made it through the most basic classes in computer science had a class that at least touched on the concept of combinations and permutations. For those that have never take computer math class, permutation is the concept of showing every sequence that can be created using every element in the set only once.

    For example: A set containing three characters, 'A', 'B' and 'C'. There are six different permutations of this set: 'ABC', 'ACB', 'CAB', 'BAC', 'BCA', 'CBA'

    Click here for a more complete description of Permutation

    If you add another character 'D' the number of permutations go to 24. So that pattern goes:

    1 character = 1 permutation
    2 characters = 2 permutations
    3 characters = 6 permutations
    4 characters = 24 permutations

    Now anyone see the pattern? 1 x 2 x 3 x 4? Or 4! (factorial). Another way to write 4! is 4 x (3 x (2 x 1)) or 4! = 4 x 3! Basic computer science professors use factorials as the basic example in recursion.

    private int Factorial(int Number)
    {
        if(Number == 0) return 1;
        else return Number * Factorial(Number - 1);
    }


    The problem in the book does not involve factorials but the actual generation of all the possible permutations of the elements in the set. I've already hinted that it involves recursion, can you figure it out?

    Take a few minutes before reading any further.

    OK, if you got it then good for you. now implement it. While your doing that, I'll explain it to everyone else.

    So, if we are going to use recursion we need to take into account two things:
    1. Solving a subset of the problem helps solve the entire problem
    2. There must be a base case where the answer is known

    Lets take the second point first. If a set only contains a single element then that set can only have a single permutation, so this can be our base case.

    Next, how can a subset of the problem help solve the entire problem? It may be easier to understand in an example:

    If you have the set 'A' 'B', all the permutations are are: 'AB' and 'BA'.

    If you now add the character 'C', you can take each previous permutation and add the new character to the front of the string. Then you just cycle the new letter through each position in the string until it is at the end. A manual example looks like this:

    C AB - A C B - AB C
    C BA - B C A - BA C

    The book suggests you write separate functions for a single character string, a two character string, a three character string and a four character string with the four first calling the three which first calls the two which first calls the single character string function.

    Once you get to writing the three and four character string function you will notice that 99% of your code looks the same in these two functions. Now you can, if it does not do so already, alter the two character function to work just like the three and four character functions.

    Now you should be able to roll these all together to get a recursive function that generates all permutations of a string of any length.

    But, this is dot net! We are object oriented, so we should be able to now alter the function to accept an array of object arrays and output a new array of object arrays. Through in a little bit of generics and you will have a completely reusable permutation generator!

    This was a fun little function to write and it got my recursive juices flowing. Maybe I'll attack a simple maze generator and solver next! Who knows?

    Welcome to "Taking Dot Net 'Old School'"

    This may not be what you first think of when you see the term "Old School". Then again it might.

    I, like many programmers, have opinions on "how" things should be done. I had never really formalized my thoughts until I read this blog post by Scott at:

    http://headinside.blogspot.com/2008/04/early-days-of-computing.html

    And specifically the quote:

    "If you want to develop something that is perceived as new and original, start by going through the older works in the field, not the newest."

    I see the truth of this all the time at my job. I see programmers that jump on the latest tool with wild abandon yet refuse to learn the grounding technologies that would teach them the proper way to use this new tool.

    You all know about the old saw, "If the only tool in the programmers toolbox is a hammer, every problem is a nail."? Well I have a corollary, "If the programmer only knows how to use a hammer, he will try to drive a nail with every tool". One programmer on my team, a long time ago and thankfully not working for the company anymore, was like that.

    I once explained his poor coding to my wife with my corollary finishing with "... so now he has this new tool, call it a high price worm drive power saw, and he is using it to drive nails into 2 by 4s." Of course my wife giggled at the mental image. It is a case of using a cool tool for the cool tools sake and to say he did, rather than taking the time to understand the underlying technology and using it where it is most appropriate.

    But, I digress. With this blog I will explore programming with dot net: new tools, old concepts and just trying things with my favorite platform.

    From Scott's blog I followed a rather crooked path (I could not even begin to retrace that path) and wound up finding a reference to an OLD computer science book filled with computer problems.

    The title? "Problems for Computer Solution" by Fred Gruenberger and George Jaffray

    The book is filled with problems from the early days of computing (circa 1965, one year before I was born!). Some of the problems confused me and some bored me but most of the amazed me.

    For example: How many people know how to calculate the day of the week that a specific date falls on? Neither did I. The book explained that one way is to use a simple algorithm called "Zeller's Congruence". It did not just have an explanation of the equation, but also ways to explore the concept further. Unfortunately, they all revolve around the base language (FORTRAN) and the base system (An IBM 1620*) that the writers used when developing these problems.

    As the posts to this blog unfold I will, among all the other things I want to do here, is explore selected problems from this book.

    Secondly, I have quite a few old computer programming magazines and I would like to go farther than Scott and explore some of the programs (I'm astounded by how many cool games were published that would make great Silverlight web games!).

    I hope that you find my posts as interesting as I do, thanks.

    ______________________________________________________


    * Believe it or not, the IBM 1620 was a decimal computer, i.e. it thought in decimal (0 through 9) instead of binary (0 and 1)!