Evil Science A whole load of stuff


Sudoku Brute – a C# implementation of the Brute-force algorithm

The brute force algorithm is "dumb" method of solving a sudoku puzzle: it sequentially tries a potential solution for an unsolved cell and then moves onto the next and attempts to find a solution for that cell, and upon finding one will move onto the next and if a solution is not found, it steps back to the previous solved cell, selects a new solution and moves onto the next again. By doing this over and over, it can be guaranteed to find a solution for any valid sudoku puzzle. However, this can be time consuming with some of the more complex puzzles taking several minutes to solve.

I have written a C# application which implements the?brute-force algorithm?to solve Sudoku puzzles. It's written using .Net 3.5 in Visual Studio 2008, and offers two different implementations of the brute-force algorithm - one uses arrays to hold data and the other using Linq to manipulate classes which hold data.?Practically, they both use the same algorithm, just different methods of implementation. From my limited testing, they both take the same time to produce a solution for any grid; the inclusion of both was just me trying different technologies.

The app is pictured below and?comes with fifty examples and allows one to add and save sudoku grids, and modify existing ones. To view an animated gif of the brute in action click here.


It's ?straight forwards to use and is controlled through the toolbar, whose functions left to right, are as follows:

  1. New sudoku
  2. Load a saved sudoku
  3. Save an existing sudoku
  4. Solved the current sudoku
  5. Reload the current sudoku
  6. Stop a solution attempt
  7. Display screen updates - selecting yes will display the solution process in real time. Selecting this option will slow down the solution process.

In addition, there are two radio buttons allowing one to select the solution class - either a Linq or array based method.


To download the executable and sample solutions, click here.

To download the source files and solutions, click here. To view the source code and run it, you'll need Microsoft Visual Studio which you can find here.

Use the above code at your own risk, and I accept no liability for any harm that may come to their computer.

I always enjoy feedback, so if you have any comments or suggestions, please leave a comment below

Filed under: C# 1 Comment

C#/.NET Fundamentals: Choosing the Right Collection Class

This is a link to an excellent article about the classes available for managing object collections.


Filed under: C# 1 Comment

Use LINQ to calculate the Greatest Common Factor of a fraction

Want to calculate the Greatest Common Factor of fraction? Use this handy piece of LINQ:

int denom = 12;
int num = 8;
int gcf = Enumerable.Range(2, num - 1).LastOrDefault(i => num % i == 0 & denom % i == 0);

//gcf == 4

It returns a value of 0 if a GCF isn't found, hence the LastOrDefault.

It's straightforwards enough I think.

Filed under: C#, Project Euler No Comments

Calculate the divisors of a number

Here are two different ways of calculating the divisors of a number using C#, something you're going to find extremely helpful when tackling Project Euler.

This method uses a for loop and a generic list.

static List<int> GetDivisors(int n)
    List<int> div = new List<int>();
    for (int ctr = n / 2; ctr > 0; ctr--)
        if (n % ctr == 0)

    return div;

This one uses an Enumerable Range and LINQ, and returns the results as a generic list.

int n = 6556;
List<int> div =
Enumerable.Range(1, n / 2).Where(i => n % i == 0).Union(new List<int>{n}).ToList();

//returns 48 results


Filed under: C#, Project Euler No Comments

Calculate the Factors of a number

This is a C sharp implementation of the method used to calculate the factors of the number, as described at Wikihow.com. It can come in quite handy when working with Project Euler.

/// <summary>
/// Calculate the Factors of a number
/// </summary>
/// <param name="n">Number to examine</param>
/// <returns>List of factors</returns>
static List<int> FactorNumber(int n)
    List<int> div = new List<int>();

    int p=2;

	if (n == 1)

	while (n % p !=0)

	    n /= p;
	} while (n % p == 0);

    } while (true);

    return div;

Usage is simple enough:

List<int> factor = FactorNumber(6552); //returns 2,2,2,3,3,7,13
factor = FactorNumber(17); //returns 17
factor = FactorNumber(25); //returns 5,5
factor = FactorNumber(60); //returns 2,2,3,5
factor = FactorNumber(100); //returns 2,2,5,5
factor = FactorNumber(45360); //returns 2,2,2,2,3,3,3,3,5,7
Filed under: C#, Project Euler No Comments

C# Combination Generator

This is a simple class that produces combinations of the provided string. It offers the following options:

  1. Unique - store only unique values.
  2. Mask - store combinations that match the provided pattern; an underscore represents a wildcard. Defaults to a length of underscores equal to the combination source string.
  3. CombinationLength - the length of the combination to be produced; defaults to the length of the combination source string.

The combinations are stored in a generic list called

The class is displayed below, and it's usage is simple.

           csCombinationGenerator c = new csCombinationGenerator();

            foreach (string s in c.Combinations) //output the 40320 combinations
                Console.WriteLine (s);

Mask and combination usage is equally simple.

            csCombinationGenerator c = new csCombinationGenerator();
            c.Mask = "8___";
            c.CombinationLength = 4;

            foreach (string s in c.Combinations) //output the 210 combinations
                Console.WriteLine (s);

Using the unique property.

            csCombinationGenerator c = new csCombinationGenerator();
            c.Unique = true;

            foreach (string s in c.Combinations) //output the 6720 combinations
                Console.WriteLine (s);

Here is the class. Copy and paste into into a new class in visual studio.

//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;

  /// <summary>
    /// Class to produce combinations of the provided string. Offers options for specifying
    /// a mask, storing unique values and length of combination to be produced.
    /// </summary>
    class csCombinationGenerator
        /// <summary>
        /// Combinations stored here
        /// </summary>
        public List<string> Combinations { get; set; }

        /// <summary>
        /// Store unique values only. If true, will slow down the generation.
        /// </summary>
        public bool Unique { get; set; }

        /// <summary>
        /// If specified, only match patterns that match.
        /// Mask specified by underscore for wildcard,
        /// </summary>
        public string Mask { get; set; }

        /// <summary>
        /// Length of the combination to be produced
        /// </summary>
        public int CombinationLength { get; set; }

        /// <summary>
        /// Produce combinations of the provided string to the provided length
        /// </summary>
        /// <param name="pString">String to produce combinations from</param>
        /// <param name="pLength">length of combination required</param>
        /// <remarks>Specifying unique only will slow the routine down</remarks>
        public void Get(string pString)
            Combinations = new List<string>();

            if (CombinationLength == 0)
                CombinationLength = pString.Length;
            else if (CombinationLength > pString.Length)
                throw new Exception("Combination length is greater than string length");
            else if (CombinationLength < 0)
                throw new Exception("Combination length is negative number");

            if (Mask == "" | Mask == null)
                Mask = new string('_', pString.Length);
            else if (Mask.Length != CombinationLength)
                throw new Exception("Mask length is not equal to string length");


            Combine(pString.ToCharArray(), "", 0);


        /// <summary>
        /// Recursive routine to perform the combinations, pDepth is reduced
        /// for each recursion and when 0 is reached the string pComb is added
        /// to t
        /// </summary>
        /// <param name="arr">Char array of characters to combine</param>
        /// <param name="pComb">The combination being built</param>
        /// <param name="pDepth">Current depth of the routine</param>
        private void Combine(char[] arr, string pComb, int pCurrentPos)
            if (pCurrentPos < CombinationLength)

                for (int i = 0; i < arr.GetLength(0); i++)

                    if (    //examine the mask
                            Mask.Substring(pComb.Length, 1) == "_"
                            | Mask.Substring(pComb.Length, 1) == arr[i].ToString()

                                //when an array item is used, make a copy of the array, excluding
                                //that value, and pass into the function.
                                arr.Where((value, index) => index != i).ToArray()
                                , pComb + arr[i].ToString()
                                , pCurrentPos + 1
                if (Unique)
                    if (!Combinations.Contains(pComb))

Filed under: C# No Comments

A simple bubble sort

A simple bubble sort which arranges the provided array of numbers from smallest to largest.

static void BubbleSort(ref int[] arr)
bool change = true;
int temp;

while (change)
change = false;
for (int i = 0; i < arr.GetLength(0) - 1; i++)
if (arr[i + 1] < arr[i])
change = true;
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
Filed under: C# No Comments

.Net Balloon window

Have you ever been frustated by the ToolTip component's lack of functionality,??i.e. you't can add a close button like?the NotifyIcon control, lack of handleable events? Be frustated no more, as a solution is at hand.

The Balloon Window for .Net will is a handy addon that offers all the functionality of the NotifyIcon control AND the ToolTip in a handy package.

Filed under: C#, Code No Comments

A perplexing problem with FCKEditor solved….

A perplexing problem I encountered with FCKEditor 2.6.3 was solved with the help of the internet. Well fancy that! Rather than recount my own problems, I'll use the words of others who encountered the same problem and paste, slightly reformat and present them, verbatim, below.

i have sucessfully implemented the editor into my .net application (vb.net) the editor works fine and configured how i wanted it, only isusse is when you go and click on the image uploader and then go to the upload tab, select the file and then click the "send it to server" button it comes up with the status bar and just hangs and does nothing. it does not upload the file all it does is show the status bar and does not move of it.

Any Sugguestions, i have altered the config.ascx file and also the fckconfig file and i belive i have pointed it to the correct file location see bellow for config.ascx and fckconfig.

Quoted from this post, where much tooing and froing occurred until a kind gentleman (or woman) posted a fix to the problem, which I reproduce for your pleasure here:

For those who have the issue where the image upload dialog uploads the image BUT the dialog hangs or stays open...here is what I did to fix it.

This is for the .net assembly 2_6_3. I based it on the help file http://dev.fckeditor.net/attachment/tic ... 2115.patch


Open the FredCK.FCKeditorV2.vs2005.csproj in Visual Studio 2005

Open the file FileBrowser > FileWorkerBase.cs

Go to line 119 and replace:

Response.Write( @"(function(){var d=document.domain;while (true){try{var A=<span style="font-weight: bold;">window.top.opener.document.domain</span>;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();" );


Response.Write(@"(function(){var d=document.domain;while (true){try{var A=<span style="font-weight: bold;">window.parent.OnUploadCompleted</span>;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();")

Compile the project and then reference the new dll file in your project.

This worked for me and I hope it helps you. The upload dialog now works on my dev XP and on the Windows Server 2003 website.

The above text was taken from here.

Filed under: C# No Comments

C#: Convert .BMP to .ICO

Some handy code:

public void BitmapToIcon(string sourceFileName, string destFileName)
// Create a Bitmap object from an image file.
Bitmap bmp = new Bitmap(sourceFileName);
// Get an Hicon for myBitmap.
IntPtr Hicon = bmp.GetHicon();
// Create a new icon from the handle.
Icon newIcon = Icon.FromHandle(Hicon);
//Write Icon to File Stream
FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate);
Filed under: C# No Comments