Programming

Markov Chain Generator in .NET

Posted in Programming, Software on February 18th, 2010 by Noldorin – 2 Comments

As part of  my current IRC.NET project (an IRC client library for .NET 4.0), I decided to create as a sample project an IRC bot that implements a Markov text generator, one of the many applications of the Markov chain, a particularly concept in probability theory. I am going to assume here that you already know what a Markov chain is and have some idea of its potential applications.

Here is the relevant C# 3.0 source code from my sample project that contains all the functionality relating to Markov chains and Markov generation. A rather nieve implementation, I would freely admit, but a simple and effective one, I’d like to think.

MarkovChain class

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace MarkovChainTextBox
{
    // Represents a Markov chain of arbitrary length.
    [DebuggerDisplay("{this.nodes.Count} nodes")]
    public class MarkovChain<T>
    {
        private static readonly IEqualityComparer<T> comparer = EqualityComparer<T>.Default;

        private readonly Random random = new Random();

        private List<MarkovChainNode<T>> nodes;
        private ReadOnlyCollection<MarkovChainNode<T>> nodesReadOnly;

        public MarkovChain()
        {
            this.nodes = new List<MarkovChainNode<T>>();
            this.nodesReadOnly = new ReadOnlyCollection<MarkovChainNode<T>>(this.nodes);
        }

        public ReadOnlyCollection<MarkovChainNode<T>> Nodes
        {
            get { return nodesReadOnly; }
        }

        public IEnumerable<T> GenerateSequence()
        {
            var curNode = GetNode(default(T));
            while (true)
            {
                if (curNode.Links.Count == 0)
                    break;
                curNode = curNode.Links[random.Next(curNode.Links.Count)];
                if (curNode.Value == null)
                    break;
                yield return curNode.Value;
            }
        }

        public void Train(T fromValue, T toValue)
        {
            var fromNode = GetNode(fromValue);
            var toNode = GetNode(toValue);
            fromNode.AddLink(toNode);
        }

        private MarkovChainNode<T> GetNode(T value)
        {
            var node = this.nodes.SingleOrDefault(n => comparer.Equals(n.Value, value));
            if (node == null)
            {
                node = new MarkovChainNode<T>(value);
                this.nodes.Add(node);
            }
            return node;
        }
    }
}

MarkovChainNode class

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace MarkovChainTextBox
{
    // Represents a node within a Markov chain.
    [DebuggerDisplay("Value: {this.value == null ? \"(null)\" : this.value.ToString()}, {this.links.Count} links")]
    public class MarkovChainNode<T>
    {
        private T value;
        private List<MarkovChainNode<T>> links;
        private ReadOnlyCollection<MarkovChainNode<T>> linksReadOnly;

        public MarkovChainNode(T value)
            : this()
        {
            this.value = value;
        }

        public MarkovChainNode()
        {
            this.links = new List<MarkovChainNode<T>>();
            this.linksReadOnly = new ReadOnlyCollection<MarkovChainNode<T>>(this.links);
        }

        public T Value
        {
            get { return this.value; }
            set { this.value = value; }
        }

        public ReadOnlyCollection<MarkovChainNode<T>> Links
        {
            get { return linksReadOnly; }
        }

        public void AddLink(MarkovChainNode<T> toNode)
        {
            this.links.Add(toNode);
        }
    }
}

As usual, I am keen to hear any sort of feedback about what is a useful little piece of code. Undoubtedly, markov chains have a number of pretty interesting applications in science and the computer world, so it would be cool to hear if other people are using this for different purposes…

WPF on IRC

Posted in Programming, Software on January 29th, 2010 by Noldorin – Be the first to comment

Being a long-time member of the ##wpf channel over on the Freenode IRC network, I thought I would bring it to the attention of any readers who are interested in this wonderful technology. Since the post is really only of interest to developers who already know WPF (or are at least keen to learn it), I shall not say anything about the technology except that it is a superb (and very modern) user interface/presentation framework for Windows applications – I strongly recommend it to anyone who develops complex (or even simple) user interfaces as a replacement for whatever library/toolkit they are already using.

The channel is currently the most popular WPF-related channel on any IRC network (of which I know), and sees regular activity, though not quite as much as we hope, hence this post! While the channel averages around 20-30 users at any time, it has not quite seen the growth it deserves as WPF gains more and more popularity. Hence, I urge anyone interested in the subject to at least pop in and check out the channel, perhaps idle around for a while. We’re a friendly lot, I promise, and will be glad to help out any newcomers!

Designs for a Computer Algebra System

Posted in Maths & Science, Programming, Projects, Software on January 8th, 2010 by Noldorin – Be the first to comment

Creating a modern computer algebra system from the ground up, as has been a plan of mine for some months now, is no trivial goal, as anyone who has even a vague conceptual understanding of computational algebra must surely know. My efforts in this area, grouped under the title of “the Syracuse Project“, have involved mostly research and large amounts of contemplation so far, but I feel that I have finally managed to formulate enough solid ideas that they are worth presenting in a short article. I was also fortunate enough to find someone on IRC (in #math-software on Freenode) with whom I could discuss and refine many of our mutual ideas. The ideas discussed in this post are the culmination of my own thoughts and much of the knowledge I gained from my conversations with Robert Smith (nickname ‘Quadrescence’) online, which has served as the basis for some of my own investigation and explanations here, in a modified form.

What I am going to focus on here falls mainly under the domain of my Euclid.NET project, which is essentially the core of Archimedes, which one might describe as the “CAS kernel”.  Think of Euclid.NET as the framework for symbolic mathematics upon which Archimedes is built. Its primary purpose is to handle such tasks as expression evaluation, simplification, differentiation, series expansion, and so on. (Bonus points if you can spot the connection between the names of Archimedes and Syracuse.)

TeX.NET, which is the primary parser (expression tree builder) for the project at this moment, has already seen a stable release, and will soon see the second with any luck. As you might guess from the name, it takes input in TeX syntax (well, actually LaTeX, with a few extensions).

To begin, I thought I would tackle one of the tougher aspects of computer algebra systems, namely, simplification. More trivial features such as expression evaluation and differentiation are essential to a CAS, yet are hardly worth an in-depth discussion, at least not for now.

So what is simplification?

Simplification, to state the banal, is concerned with making an expression more “simple”. Unlike many every terms that have been borrowed by mathematics, “simple” or “simplification” truly does not have a more rigorous definition. The problem here largely stems from the fact that the definition of what is simple is somewhat fluid – it depends to a great extent on the context. To illustrate this nature more concretely, here a few examples.

  1. (x+1)^2 or x^2 + 2x + 1?
  2. y^{-3.5} or 1/y^{3.5} or 1/(y^3 \sqrt{y})?
  3. \tan x \sin x or \dfrac{\sin^2 x}{\cos x}?
  4. e^{A+(2x-y)} or e^A\left[\dfrac{e^{2x}}{e^{y}}\right]?
  5. 4 \sqrt{x^3 + 6x^2 + 9x} or 4(x + 3)^2 \sqrt{x} ?

A simple expression treeA visualisation of a very simple expression tree. The equivalent infix expression is (2 + 2) + (2 + 2) + (3 + 3). Note that in general such trees are not restricted to be binary.

I think that anyone who has had sufficient experience using maths and manipulating many formulae and expressions will realise that in some scenarios, one of the given equivalent expressions in 1 to 5 is desired in a certain scenario, while another is desired in a second situation. Hence, any conceivable simplification algorithm cannot be treated as a rigid mechanical process, bur rather must adjust itself depending on the parameters it is given, which hint at the sort of result that is desired.

When humans perform simplification of mathematical expressions, they often use so-called intuition, developed from much prior experience, along with trial and error, to (in most cases) quickly and accurately simplify maths. It is inevitable that even the best mathematicians hit dead ends when trying to simplify complicated expressions. A computer, perhaps unsurprisingly, cannot do any better. Moreover, mathematical simplification is, in my view, one of the few aspects of mathematical methodology that overall better suits a holistic intelligence, rather than the traditional sequential one that is most often associated with maths (theorem proving being a notable exception). In fact, mathematics is not all so logical and all-encompassing as even mathematicians not long ago thought – thanks to the magnificent Incompleteness Theorem proposed by Kurt Godel in the 1930s – this is however a subject for another day.

How can we measure simplicity?

Fortunately, and perhaps surprisingly, the field of evolutionary computation presents a rather handy way of treating the “simplicity” of expressions, that is, a fitness function – in its most abstract sense, something that measures the absolute “fitness” of any given solution for a certain optimisation problem (most commonly genetic algorithms, which lent the term “fitness”). The “fitness” may be thought of qualitatively as the value, worth, or suitability of a particular solution. The solutions, in this case, are of course expression trees.

To begin, it is greatly helpful to reduce the problem by extracting a certain (small) number of parameters from the expression tree, rather than trying to analyse the entire thing holistically. This reduces the parameter space (the set of all possible parameters) dramatically, which is typically highly beneficial in optimisation problems. The fitness function itself is allowed to take any form in general, though we shall see shortly that one or two classes of function in particular are desirable. For now, let us just focus on the set of parameters. After some consideration, I came to the conclusion that any effective parameter space must consist of the following variables:

  • Size of the expression tree (i.e. the number of nodes)
  • Height of the expression tree  (i.e. the number of layers)
  • Width of the expression tree (i.e. the number of nodes in the bottom layer).

These are all of course integer values, and thus the value of the function is restricted to lie within the set of integers. After building up an image that measuring simplicity is a tricky thing, this may seem like a rather straightforward framework; indeed, it is in some ways, thought it is worth noting that the apparent problems arise when we decide what function to use and when it should be applied. The reasons for the choice of these parameters should become apparent soon.

Let us first consider a basic fitness function that simply weights each parameter individually in a linear combination. In other words, the fitness function, F(S, H, W) may be defined as the following, where S, H, and W correspond to the size, height, and width of the expression tree respectively.

F(S, H, W) = aS + bH + cW

The constants a, b, c may be any integer (postive or negative), and should be passed to the simplifier routine rather than predefined, according to the desired output. It should be quite evident that by choosing different magnitudes as well as signs for these constants, each of the three parameters may be independently rewarded or penalised to greater or lesser extents. The question you might then ask is: why not a more complicated function depending on S, H, and W? My answer is a straightforward one: there is no need. A linear combination of terms gives enough control over the desired function that extending to the function to add higher-order or even exponential terms would be quite pointless and arbitrary. I have, however, far from closed my mind on this matter – as I design and test the system progressively, certain discoveries may be made that suggest a slightly different approach.

Indeed, my only other real consideration for a fitness function thus far is one of even more basic form. Suppose, for example, that the fitness function only depended on two things: a) which parameter should be prioritised, b) whether this parameter should be promoted or demoted. The other two parameters would simply be minimised in the case that the first shows no preference between two trees. I have not finalised the implementation of this, but hopefully this brief description should give you an idea.

I now only leave, as an exercise to the reader, the five example expressions given in the previous section, and considered how any desired result (simplified form) can be achieved through the selection of the appropiate fitness function (using either of the two I have just proposed). Of course, feel free to post a comment regarding any queries or findings you have regarding this matter.

An effective algorithm for simplification

So far, I have discussed how simplicity can be measured in absolute terms, and how in this way the most “simple” of a set of solutions (expression trees) can be chosen as the result of the algorithm. What I have not really mentioned, however, is how an algorithm might actually search out the possible solutions. Although the nature of the algorithm is mainly independent of the fitness function  and the evaluation of expression trees, it is helpful to discuss this second so as to give a clearer image to the approach as a whole.

Simplification when done by a computer, as when done by humans, involves at its heart the application of a large number of mathematical rules that transform expressions. To give some examples of a few of the more basic rules:

  • x + 0 \rightarrow x
  • 1 * x \rightarrow x
  • x * x \rightarrow x^2
  • x * (y / x) \rightarrow y
  • x^2 - y^2 \rightarrow (x + y)(x - y)
  • \sin^2 x + \cos^2 x \rightarrow 1

Given a complete set of all simplification rules, we can find a path (or derivation) between any two equivalent expressions. (In theory, this is no issue, since the set is finite, though rather large. The practicality of  all the required rules is another issue that I will not go into here.) Note that the rules are bidirectional; they allow you take a simple expression and sequentially transform it into an arbitrarily complex, yet still identical one. (For example, x \rightarrow x + 0 - 0 + 0 - 0 + 0.)

Assuming (quite reasonably) that this assertion that a “finite number of application of simplification rules can derive any equivalent expression from the original” is valid, we must then consider how the search should proceed. Under the utterly naive brute force approach, the algorithm is clearly non-terminating, but we can do a lot better than this.

The search algorithm is all about compromisation in essence. If we search every possible derived expression (up to a certain size), then it could take an unreasonably length of time to simplify even relatively tiny expressions. On the other hand, we make too many assumptions and cut off many branches in the search tree prematurely, the algorithm may terminate quickly, though not necessarily with the simplest solution (or even anything close). Hence, the idea of using genetic algorithms, albeit initially appealing, is in my view to restrictive to a problem that requires a “perfect” answer in most cases, and should not have any stochastic nature.

My currently planned approach is one that does not differ greatly from a simple brute force evaluation of all the simplification paths. The main improvement is one that falls out rather naturally from using a fitness function. The idea is that each node of the search tree is evaluated by the fitness function upon its creation, and if the fitness is below a certain (specified) threshold, the search from that particular node terminates. For a start, this prevents originally small/simple expression trees being transformed into ones that are absurdly large, while still allowing some limited expansion of expression trees in the hope that they may later be simplified very effectively. Many nonsensical (what we might call counter-intuitive) paths of reduction of the expression would also be eliminated in a similar way. There is also one practical problem of important note here: many disparate simplification paths along the tree do converge to the same solution during a search (some quite quickly), so it would be quite foolish to branch twice from identical nodes of the search tree. Instead, we really want to cache any nodes (expression trees) already visited during the search process, and not compute their descendants (derived children) more than once. A simple hash table (set, in fact) would seem like the most effective way of accomplish this. Creating an efficient and relatively collision-free hash function for an arbitrary tree structure is however no trivial task. I was to get a number of quite sensible and useful responds when I asked the question on StackOverflow.

Apologies if this discussion of “search trees” and “expression trees” and their corresponding nodes has led to some confusion regarding what is what. It is most important to recognise that the node of a search tree is itself an expression tree (what I sometimes call a “solution” to the “simplification problem”). Due to the risk of losing reader interest at the cost of an even longer post, I shall stop my ramblings here, and leave further elaboration of the search algorithm for another post.

The future of the project

What has been discussed so far is largely theoretical, yet I have tried to present it in such a way that the method of implementation is for the most part self-evident. Work on this project will likely proceed slowly in the short-term future, though as it advances, the features will surely solidify. I am hoping that at least by summer there should be some tangible results to these efforts. Regardless, I shall try to give status updates along the way.

Read-Only Collections in .NET

Posted in Programming on December 22nd, 2009 by Noldorin – 1 Comment

In the recent course of developing my IRC.NET library I was hit (quite plainly) by a scenario where I needed to expose an immutable (read-only) version of a generic Dictionary object, and found no immediate solution in the BCL (base class library). Shortly thereafter I had a similar situation, except involving the exposing of a generic HashSet object. Unfortunately, unlike for Collection<T> objects (or in fact anything that implements IList<T>), there are no read-only equivalents of these classes in the BCL, in the manner of ReadOnlyCollection<T> – not even, I may add, in the latest .NET 4.0 Beta 2. Many developers have complained about the lack of a ReadOnlyDictionary class, and a quick Google search should show up several older and more recent blog posts as well as a couple of Microsoft Connect reports on the subject. No news from the guys at Microsoft, unfortunately.

Note: Don’t be fooled by the naive solution of simply casting the collection object to an IEnumerable<T> and exposing that instead – I’ve seen this on more than one occasion in code I’ve viewed. The problem here, in case it isn’t obvious, is that the user can simply cast the IEnumerable<T> back to the mutable collection type and modify that. More often that not, you want to expose more than just an iterator, anyway.

Having racked my mind for a quick and elegant solution to this issue of exposing read-only collection objects, and not being enticed to tarnish an otherwise well-designed library with nasty hacks, I decided that I would implement immutable wrappers around the IDictionary<TKey, TValue>and ISet<T> interfaces. It turned out this in fact only required a minimal amount of effort, yet I was pleased with what I ended up with, and feel that my implementations are complete and well crafted enough to share with the community.

Download the ReadOnlyDictionary<TKey, TValue> class.

Download the ReadOnlySet<T> class.

Suggestions and comments on the design and code are, of course, most welcome.

Leaner CSS

Posted in Programming, Software, Web Design on December 14th, 2009 by Noldorin – Be the first to comment

In my wanderings today, I just happened to stumble across a relatively new project by the name of LESS, which might appeal to anyone interested in web design. LESS has the simple of aim of making CSS “leaner” by extending the language with such constructs as variables, mixins, operations, and nested rules.

Now, I haven’t gotten around to trying it out yet, but it immediately strucky me as a pretty cool little system – it seems to vastly extend the usability of CSS in a very similar way to what JQuery did with Javascript (despite plain CSS being somewhat less horrible than plain Javascript). We’ll have to wait and see whether this project takes off however, though I have an inkling it just may – it has the innovation, for a start.

I will undoubtedly report back whenever I can find some free time to squeeze between my studying and ongoing computational projects. For the moment, I thought I would simply spread the word, as the creators seem most keen to promote.

TeX.NET 0.1.0 released

Posted in Maths & Science, Programming, Projects, Software on October 8th, 2009 by Noldorin – Be the first to comment

Some news to report at last! I’ve just released the first the first beta version of my TeX.NET project over at Launchpad. Both the source (with unit tests) and binaries of what might be called “a parsing and writing library for mathematical expressions written in the TeX format”; programmed, of course, in C# 3.0 (with some rudimentary F# bindings).

This project hasn’t exactly been the focus of my blog posts recently (or at all, for the matter), mainly because I’ve found that working on the thing has taken almost all of my free time over the past month or so.  As I have come to learn, putting effort into promotion of ones ideas and work is not a wise thing to do before they have proper substance!

Since I’m not one to reword any text that I’ve already (quite carefully) written, I shall quote the project summary over at Launchpad:

TeX.NET is a library for the .NET Framework 3.5 that provides lexical analysis and parsing of mathematics written in the TeX format into expression trees, and conversely the writing of expression trees in the same textual format. The purpose of the library is to provide a useful framework for inputing, outputing, and manipulating complex mathematical expressions.

Now, you may of course be curious where I’m taking this project in the grand scheme of things. (Indeed, a library for parsing of mathematical expressions isn’t terribly useful on its own.) Although it’s far from an in-depth explanation of the end goals and my approach, I suggest you check out the Syracuse Project, which is the “container” or “super-project” for TeX.NET, among other related libraries and programs. I can however say that I will be shifting my efforts more towards the Euclid.NET project, now that I have a stable initial version of the requisite parser/writer library. It is bound to be the subject of one of my upcoming posts, anyway.

So, if anyone is inclined to give my TeX.NET library a whirl (or better yet, some further rigorous testing), I would urge gratefully them to do so. Any sort of feedback on this project is welcome, as with all of my endeavours. My aim the moment is mainly to garner a nucleus of interest and see this library applied to great things!

Demo of Euclid.NET Launched

Posted in Programming, Projects, Software on September 20th, 2009 by Noldorin – Be the first to comment

Just a quick note that I’ve recently put up an interactive demo of my Euclid.NET project (symbolic mathematical framework for .NET).  This project is based off my TeX.NET parser, which is currently all of which the demo presently consists. I hope to both expand and document the support for the parser soon, as well as starting some serious work on Euclid.NET specifically (most likely, a symbolic differentiator to begin).

Writing a Parser in C#

Posted in Programming, Projects on September 14th, 2009 by Noldorin – 1 Comment

This is just a quick note about a particularly useful article that I stumbled across in the process of writing my TeX Math parser (to be described in full in an upcoming post). The article Grammars and parsing with C# 2.0 is a wonderful introduction to writing a lexer and parser for any language represented by a context free grammar (more accurately, a parser expression grammar).

The document is written in a refreshingly lucid fashion and what is more there are straightforward examples in C# regularly interspersed. (I am not overly-inclined to give out such praise!) For a topic so mired in confusion and complexity, I though this would be an especially helpful link to share with any C# coders who are interested in entering the field, as I am currently doing myself. The content is something I believe any coder with a solid background in OOP should be able to drive straight into without much difficulty (that isn’t to say you will glean everything from a one-pass read). Of course, it is only a guide for relative beginners (albeit a fairly thorough one) – if anyone happens to have other basic or more advanced texts on the subject of similar quality, it would be great to compile a small collection of selective resources on the subject, and expand this post in the process.

Hungarian Algorithm in C#

Posted in Maths & Science, Programming on September 8th, 2009 by Noldorin – 23 Comments

The Hungarian algorithm, also known as the Kuhn-Munkres algorithm, is well-known to be the most efficient algorithm for solving the assignment problem. In fact, it does what is considered by many to an exponential time algorithm (more specifically, factorial time), in O(n3).

The Wikipedia page describes the general form of the problem quite well.

There are a number of agents and a number of tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task in such a way that the total cost of the assignment is minimized.

However, the implementation of this algorithm is far from trivial. In fact, for all my Googling, not a single implementation in C# turned up (though there was at least one in each of C, C++, Java, and Python). Given this opportunity, I took on the task of porting this code given on this page in the Ada language, to C# 3.0. With almost 300 lines of code, and a bit of debugging with the sample problem,

You may download the complete code for the algorithm, in C# 3.0, here. It is contained within a single static class that exposes an extension method that operates on a matrix (2D array), for ease of use. Although I believe that as an almost line-for-line port of the Ada code, there should not be any issues with my implementation, any bug reports would be appreciated.

Updated 15/10/09: Several bug fixes have been made that fix issues (most noticeably, endless looping) for non-square as well as various other sorts of matrices.

Updated 24/10/09: Fixed bug (endless looping) that affects large variety of matrices involving ConvertPath function.

Google Code Jam in C#

Posted in Fun, Programming on September 3rd, 2009 by Noldorin – Be the first to comment

The Qualification round for Google Code Jam 2009 is entering its closing hours, and having submitted my solutions for the three problems, I thought I would share just the framework I set up for solving the problems. This is something I originally began  writing for last year’s Code Jam, but I have updated it for the altered format this year, as well as expanded the functionality.

The framework consitsts of a class that has a number of simple methods for accessing the input data as well as writing the output cases. The main convience is its abstraction of the text file I/O  into simple methods that deal with arrays (and arrays of arrays) of primitive types. As a bonus, all the relevant output information, as well as the execution time, is printed to the standard out stream (console window).

using System;
using System.IO;
using System.Text;

public class CodeJamProblem : IDisposable
{
    protected int caseNumber;

    protected StreamReader textReader;
    protected StreamWriter textWriter;

    private bool disposed = false;

    public CodeJamProblem(string inputFileName)
    {
        this.InputFileName = inputFileName;
        this.OutputFileName = Path.ChangeExtension(this.InputFileName, ".out");

        this.textReader = new StreamReader(this.InputFileName);
        this.textWriter = new StreamWriter(this.OutputFileName);

        this.caseNumber = 1;
        this.StartTime = Environment.TickCount;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                this.ElapsedTime = Environment.TickCount - this.StartTime;

                textReader.Dispose();
                textWriter.Dispose();

                Console.WriteLine("Elapsed time: {0:#,#0}ms", this.ElapsedTime);
                Console.Beep();
                Console.ReadKey(true);
            }
        }

        disposed = true;
    }

    public int StartTime
    {
        get;
        private set;
    }

    public int ElapsedTime
    {
        get;
        private set;
    }

    public int CurrentCaseNumber
    {
        get { return this.caseNumber; }
    }

    public bool InputAvailable
    {
        get { return this.textReader.Peek() != -1; }
    }

    public string InputFileName
    {
        get;
        private set;
    }

    public string OutputFileName
    {
        get;
        private set;
    }

    public void OutputCase(params object[] values)
    {
        var parts = new string[values.Length];
        for (int i = 0; i < parts.Length; i++)
            parts[i] = values[i].ToString();
        OutputCase(string.Join(" ", parts));
    }

    public void OutputCase()
    {
        OutputCase((string)null);
    }

    public void OutputCase(string value)
    {
        WriteLine("Case #{0:#0}: {1}", this.caseNumber, value);
        this.caseNumber++;
    }

    public void WriteArrays<T>(T[][] entries)
    {
        for (int i = 0; i < entries.Length; i++)
            WriteArray(entries[i]);
    }

    public void WriteArray<T>(T[] values)
    {
        var parts = new string[values.Length];
        for (int i = 0; i < parts.Length; i++)
            parts[i] = values[i].ToString();
        WriteLine(string.Join(" ", parts));
    }

    public void WriteLines(string[] lines)
    {
        for (int i = 0; i < lines.Length; i++)
            WriteLine(lines[i]);
    }

    public void WriteLine(string format, params object[] arg)
    {
        Console.WriteLine(format, arg);
        this.textWriter.WriteLine(format, arg);
    }

    public void WriteLine(string line)
    {
        Console.WriteLine(line);
        this.textWriter.WriteLine(line);
    }

    public int[][] ReadIntArrays(int count)
    {
        var entries = new int[count][];
        for (int i = 0; i < entries.Length; i++)
            entries[i] = ReadIntArray();
        return entries;
    }

    public int[] ReadIntArray()
    {
        var parts = ReadParts();
        var values = new int[parts.Length];
        for (int i = 0; i < values.Length; i++)
            values[i] = int.Parse(parts[i]);
        return values;
    }

    public double[][] ReadDoubleArrays(int count)
    {
        var entries = new double[count][];
        for (int i = 0; i < entries.Length; i++)
            entries[i] = ReadDoubleArray();
        return entries;
    }

    public double[] ReadDoubleArray()
    {
        var parts = ReadParts();
        var values = new double[parts.Length];
        for (int i = 0; i < values.Length; i++)
            values[i] = double.Parse(parts[i]);
        return values;
    }

    public string[] ReadParts()
    {
        return ReadLine().Split(' ');
    }

    public string[] ReadLines(int count)
    {
        var lines = new string[count];
        for (int i = 0; i < lines.Length; i++)
            lines[i] = ReadLine();
        return lines;
    }

    public string ReadLine()
    {
        return this.textReader.ReadLine();
    }
}

Hopefully this will assist someone other tham myself, though I suspect most contestants have set up something of the same sort. I will continue to make minor modifications over the duration of the contest, and will update this post to reflect them.

Regarding the Qualification round itself, the problems have proven to be fairly interesting. (Well, the first was rather trivial if one is honest.) Now, only to wait for the upcoming Round 1, and hope the problems don’t become too much more challenging!