JOIN
Get Time
features   
Beginning TopCoder Competition with C#.Net

Author
By ali_raza_shaikh
TopCoder Member

1. Introduction
C# -- usually pronounced "CSharp" -- has been around since 2001. C# is an object oriented, programming language, with a C-based syntax much like C++ or Java. The first version of the C# programming language was released with the .NET Framework 1.0 back in 2001. From the beginning, C# showed great signs for rapid application development and is targeted for developing software components to be used in distributed environments. C# is such a language (or you could say that .NET is such a platform) that most programmers will be comfortable with it in no time and will continue to explore the rich class libraries provided by the framework.


Since its release, its usage at TopCoder has increased each year. C# is currently not the most common language for competitions at TopCoder, but Petr demonstrated what C# is capable of with wins at the 2006 TCO and TCCC, along with 25 SRM wins. This article is intended to help newcomers, especially new High School competitors, get up to speed so that they, too, can take advantage of C#'s strengths in TopCoder competitions.

2. Getting Started - Registration
To participate in any TopCoder Algorithm Competitions, you must first register with TopCoder. Registration will allow you to participate in the Single Round Matches as well as other competitions at TopCoder. To Register.

Once you're registered, check out the Competition Arena. You can launch the Arena from the TopCoder site or you can launch it directly by downloading the Java Web Start Application file. Don't have JWS? Download it on java.sun.com.


3. Getting Started - Environment
So, if you are getting started with C# or are doing a lot of C# programming, you will probably find yourself using Visual Studio.Net. Visual Studio is an Integrated Development Environment (IDE) with a pretty fancy source code editor, edit-and-continue debugger, syntax highlighting, intelligence, code snippets, refactoring and many other cool features. Visual Studio is not the only IDE in the market to write C# programs -- there are many others, like ISharpCode and MonoDevelop (if you are a Linux fan), or you can also download the freely available Microsoft C# 2005 Express Edition.

4. Getting Started - Practice
New to TopCoder? New to Algorithm Competitions? Then it's a good idea to try out some practice problems in the Arena before you tackle your first SRM.

  1. Your first step in the Arena should be to set your default language to "C#" (this is under "Options"/"Setup User Preferences").

  2. Next, move on to the practice rooms by clicking "Practice Rooms"/(Your Choice). Currently you can check out the past SRM, Tournaments and TCHS Problems. To get the feel of the competition go to any room you like.

  3. (click to enlarge image)

  4. Once you've moved into one of the practice rooms, click the "select one" drop down box, and choose the "250" question (the easy question from that problem set) to get started. A new window will open up with the details of the problem. This window is divided into different sections like Problem Statement, which describes the problem, Coding Area, where you enter your solution, Competition Time & Status and different options to Save, Clear, Compiler, Test and Submit your code.

  5. (click to enlarge image)

  6. The Problem Statement section describes the problem in terms of Statement, Definition, Constraints and Example Test Cases. Statement basically describes the problem to be solved; Definition shows the Class Name and Method Signature that are required for submission, Constraints explains the input format and limits and Examples show some test cases you should run against your code before submission.

5. Working Toward Your Submission - Development
You have registered, opened up your IDE, launched the arena and selected the practice room & problem -- now we are getting down to business. As you work on your submission, you can code the problem directly in the Coding Area, just like Notepad, but it becomes increasingly difficult to write code directly without a proper IDE as problems become more difficult and you need to debug your problem more often. I probably spend 90% of my C# programming time using Visual Studio.Net and then copying the finished code back to the coding window. As you become more comfortable, you may also want to investigate some of the many Arena Plugins available that will automate the use of an external IDE during development, generate stub and test code, or make the code window more feature rich.

Based on the definition in our practice problem's problem statement, we can build "stub code" that will look like this

public class Fractile
{
    public int fractile(int[] x, int p)
    {
        // Code Here
        return 0;
    }
}

Note that your class name, method name, and parameter types must all match the problem definition. You can name the parameter names whatever you want, but it is convenient to just copy and paste the entire Method Signature.

When using Visual Studio.Net for development (C# Console Project), your "stub code" will look like this

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace TopCoder
{
    public class Fractile
    {
        public int fractile(int[] x, int p)
        {
            // Code Here
            return 0;
        }

        static void Main(string[] args)
        {
            // Fractile Class Object
            Fractile objFractile = new Fractile();

            // Input
            int[] x ={ -3, -5, 2, 1 };

            // Calls the method and output the result
            Console.WriteLine(objFractile.fractile(x, 50));
        }        
    }
}

C# is a case-sensitive programming language, therefore Main() and main() are two different methods. The entry point for a C# program must be called Main(). The Using statement helps us to play around with the Framework Class Library, which provides useful functionalities. By default Visual Studio uses the following namespaces:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

It's worth exploring the namespaces that will help you during the competitions. Some of the cool functions that are provided include:

  • System.Math - provide useful things like Abs, BigMul, Ceiling, DivRem, Exp, Floor, Min, Max, Pow, Log, Round, Truncate and many more.
  • System.DateTime - provides useful functions for date processing.
  • System.TimeSpan - provides useful functions for time processing.
  • System.Convert - Really helpful for Typecasting
  • System.Collections - provides LinkList, Queues, Stack, List, ArrayList, Dictionary and many more
  • System.Text - provides really good regular expression class for pattern matching & input validation and also the StringBuilder class for string manipulation.

Working with Data Types
The following tables shows some of the basic data types that are used during algorithm competitions.

C# Primitive C# Alias Description
Boolean bool Indicates a true or false value.
Char char 16-bit Unicode character.
Decimal decimal High-precession numerical type.
Double double Double precession floating point value.
Single float Single precession floating point value.
Int32 Int 32-bit signed value.
Int64 long 64-bit signed value.
String string Immutable string of character values

During the competition, you will also face problem statements dealing with arrays of the above mentioned data types like the Fractile Class where X is a one dimensional integer array. One important thing here is that all the arrays in C# are 0 based, so if you want to access the first element of X you will write it as X[0].

// A two dimensional array of Int's
int[,] intArray = new int[10,10];

// A one dimensional array of references to Strings 
string[] stringArray = new string[10];

Parsing Your Input
This is one of the things you'll face more often than not during competitions: the input is provided as a string or string[], where the string contains several text fragments separated with delimiters. Suppose that you get a input something like this "Karachi 21 Hyderabad 221 Lahore 41 Islamabad 51", here the input contains the data in the following format CityName CityCode, so you have to parse through the string to get the required information. One of the handy functions in C# is to Split() the string. If your input is in a format like this "12:13:14", then you can also use Split(':').

public static int GetCode(string CityNameAndCode, string CityName)
{
      int Length=CityNameAndCode.Split().Length;

      // Iterate through the City Names and then return the City Code
      for (int i = 0; i < Length; i += 2)
      {
          if (CityNameAndCode.Split()[i] == CityName)
                return Convert.ToInt32(CityNameAndCode.Split()[i + 1]);
      }

       // If City is not found return -1
       return -1;
}

Formatting Your Output
Some of the SRM problems require you to format the output as well, such as the FormatAmt (SRM 149, Div2 Easy) problem, in which you must output the number with dollar sign, commas and zeroes up to 2 decimal places. By using the standard numeric format specifiers, though, you can get the desired output format within no time and have a quick submission. Check out the list of all the standard numeric format specifiers here.

public class FormatAmt
{
    public string amount(int dollars, int cents)
    {
        double d = dollars;
        d += ((double)cents) / 100;
        return d.ToString("C");
    }
}

6. Compile, Test and Submit
So, you have coded the problem and are ready to make your submission. You should copy and paste the code from Visual Studio (or the IDE of your choice) to the Coding Area, remove the Main Function and the namespace before submitting, and compile the code -- after a successful compilation, test the code against the provided test cases. After running a test case, a window will pop up to show the test case result, including the time taken by the code and the program output. You can change the input argument and provide the custom values on which you want to test your code. One important thing here is to check your code with the boundary cases, since the TopCoder system only allows 2 seconds for code execution. If the code passes all the test cases then submit the solution.


During practice sessions, you can run the System Test by clicking Practice Option -< Run System Test, which will verify your code against different test cases. A new window will open up showing different test case results, including the expected value, the received value and the time taken by the problem.


(click to enlarge image)

Further Reading
This article only covered a few things regarding C#.NET, but hopefully it will help you get started. You may also want to check out the article "Beginning Algorithm Competitions with VB.NET," which covers many of the commonalities between C# and Visual Basic. Keep on practicing, and you'll have the basics down in no time. Good luck!