Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Saturday, 19 May 2012

Supposed to be the introduction episode Smile

Dynamic

static void Main(string[] args)
        {
            object x = new List<int>();
            //will give an InvalidCastException at runtime
            string y = (string) x;
            Console.WriteLine(y.Length);
        }
object x = "hello";
            string y = (string) x;
            Console.WriteLine(y.Length);

gives answer of 5

object x = null;
            //we can cast a null reference
            string y = (string)x;
            //but we cant dereference it..get a nullReferenceException
            Console.WriteLine(y.Length);

sdf

//don't think of x at any type... sort out at execution time
dynamic x = "hello";
//5
Console.WriteLine(x.Length);

//an array
x = new int[] {10, 20, 30 };
//3
Console.WriteLine(x.Length);

from

int x = 123;
            int y = 10;
            Console.WriteLine(x-y);

image

using ildasm to disassemble the debug assembly.  The nop statements are for debug.

This is op code (IL).. i4 is like int32

load 123 and put into stack position 0

load 10 and put into stack position 1

then put into dynamic types

Named Arguments

Whats an argument and whats a parameter?

    static void Main(string[] args)
    {
        //provide an argument
        Foo("hello");
    }

    //x is a parameter
    static void Foo(string x)
    {
        Console.WriteLine(x);
    }
}

image

Got it the wrong way round.. hard to tell which is which in MessageBox.Show

static void Main(string[] args)
        {
            //named argument C#4
            Foo(x: "hello", y:"Rob");
            //referenced System.Windows.Forms
            MessageBox.Show(caption:"title", text:"body");
        }

        //x is a parameter
        static void Foo(string x, string y)
        {
            Console.WriteLine(x + " " + y);
        }

better!

Optional Parameters

    static void Main(string[] args)
    {
        //named arguments
        Foo(y: "Rob");
        Foo(y: "Dave");
        Foo(y: "Mike");
        Foo(y: "Bill");
        Foo("Hi", "Anders");
        Foo();
    }

    //optional parameters
    //if first parameter is optional all have to be
    static void Foo(string x = "Hello", string y = "Everone")
    {
        Console.WriteLine(x + " " + y);
    }
}

Covariance and Contravariance

Some code here.. poster child of the more used covariance is IEnumerable<T>.. look for out keword.  And it is to do with hierarchies.

class Fruit { }
    class Banana : Fruit { }
    class Apple : Fruit { }

    //interface IEnumerable<out T>
    //{
    //    IEnumerator<T> GetEnumerator();
    //}

    //interface IEnumerator<out T> : IDisposable
    //{
    //    T Current { get; }
    //    bool MoveNext();
    //    void Reset();
    //}

    //covariance values coming out of an interface
    //usually happens with IEnumerable of T
    interface IFoo<out T>
    {
        T GiveMeAnInstanceOfT();
        //void TakeanInstanceOfT(T instance);
    }

    //contravariance is in

    class Program
    {
        static void Main(string[] args)
        {
            //List<Banana> bunchOfBananas = new List<Banana>();
            IFoo<Banana> bunchOfBananas = null;

            //cant convert from a list of banana to a list of fruit
            //List<Fruit> fruitBowl = new List<Banana>();

            //List<Fruit> fruitBowl = bunchOfBananas;
            //fruitBowl.Add(new Apple());

            //Banana banana = bunchOfBananas[0];

            //IEnumerable - sequence..cant add.. can only observe
            //IEnumerable<Fruit> fruitBowl = bunchOfBananas;
            IFoo<Fruit> fruitBowl = bunchOfBananas;
        }
    }
| | # 
# Tuesday, 27 December 2011

variables or local variables – declared inside methods

fields – variable (public or private) that is a member of a class

property – has a getter or setter

| | # 
# Sunday, 10 April 2011
keithDave

About a week ago Keith and I went on a ‘tramp’.. thats trekking.  We discussed Sudoku (apologies to Helen, Phil, Nora and others for starting the challenge without you..there was lots of time while walking to discuss strategy).

TDD

A single test project is VS2010.  Everything in one file (!) and static methods to make starting easier.

Coding strategy was to firstly:

    • find a way to check the sudoku was solved
      • Do all horizontal lines have only 1 to 9 used once
      • Do all vertical columns have 1 to 9 used once
      • Do all 3*3 squares have 1 to 9 used once

So I wanted a method to check if Array has only 1 instance of each number.

[TestClass]
public class UnitTest1
{
// Arrays are [row, col]
// 0,0 0,1 0,2
// 1,0 1,1 1,2

// SECTION 1 - tests are all about testing if the sudoku is solved
// Single Array
[TestMethod]
public void SingleArrayCheckerFailsWhenArrayTooShort()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
bool result = DoesArrayHaveOnlyOneInstanceOfEachNumber(numbers);
Assert.AreEqual(false, result);
}

and the Method:

public static bool DoesArrayHaveOnlyOneInstanceOfEachNumber(int[] arrayOfNumbers)
{
if (arrayOfNumbers.Length != 9)
return false;

if (arrayOfNumbers.Contains(0))
throw new Exception("checking of a line array contains a 0");

int[] howManyInstancesOfEachNumber = new int[9] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

for (int i = 0; i < 9; i++)
{
int valueOfCurrentNumber = arrayOfNumbers[i];
howManyInstancesOfEachNumber[valueOfCurrentNumber - 1] += 1;
}

foreach (var result in howManyInstancesOfEachNumber)
{
if (result != 1)
return false;
}

return true;
}

An array is Enumerable.

then write the tests

[TestMethod]
public void AllHorizonalLinesPass()
{
int[,] sudokuArray = new int[9, 9]{ {1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9}
};

bool result = DoAllHorizontalRowsPass(sudokuArray);
Assert.AreEqual(true, result);
}

[TestMethod]
public void AllVerticalColsPass()
{
int[,] sudokuArray = new int[9, 9]{ {1,1,1,1,1,1,1,1,1},
{2,2,2,2,2,2,2,2,2},
{3,3,3,3,3,3,3,3,3},
{4,4,4,4,4,4,4,4,4},
{5,5,5,5,5,5,5,5,5},
{6,6,6,6,6,6,6,6,6},
{7,7,7,7,7,7,7,7,7},
{8,8,8,8,8,8,8,8,8},
{9,9,9,9,9,9,9,9,9}
};

bool result = DoAllVerticalColsPass(sudokuArray);
Assert.AreEqual(true, result);
}

[TestMethod]
public void AllSquaresPass()
{
int[,] sudokuArray = new int[9, 9]{ {1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{7,8,9,7,8,9,7,8,9},
{7,8,9,7,8,9,7,8,9},
{4,5,6,4,5,6,4,5,6},
{1,2,3,1,2,3,1,2,3},
{4,5,6,4,5,6,4,5,6},
{1,2,3,1,2,3,1,2,3},
{7,8,9,7,8,9,7,8,9},
};

bool result = DoAllSquaresPass(sudokuArray);
Assert.AreEqual(true, result);
}

then make them pass:

public static bool DoAllHorizontalRowsPass(int[,] sudoku)
{
for (int row = 0; row < 9; row++) // go over each horizontal line
{
int[] horizonalLineArray = new int[9];
for (int col = 0; col < 9; col++) // get each number in that line and put into a new horizontalLineArray
horizonalLineArray[col] = sudoku[row, col];

if (!DoesArrayHaveOnlyOneInstanceOfEachNumber(horizonalLineArray))
return false;
}
return true;
}

public static bool DoAllVerticalColsPass(int[,] sudoku)
{
for (int col = 0; col < 9; col++) // go over each vertical line
{
int[] verticalLineArray = new int[9];

for (int row = 0; row < 9; row++) // get each number in that vertical line and put into a new verticalLineArray
verticalLineArray[row] = sudoku[row, col];

if (!DoesArrayHaveOnlyOneInstanceOfEachNumber(verticalLineArray))
return false;
}
return true;
}

public static bool DoAllSquaresPass(int[,] sudoku)
{
int rowStart = 0;
int rowEnd = 2;
int colStart = 0;
int colEnd = 2;

int squareCounter = 1;
while (squareCounter < 9) // take each 3*3 square and test it
{
int[] allNumbersInSquareArray = new int[9];
// go over first 3*3 square
int counter = 0;
for (int row = rowStart; row <= rowEnd; row++)
{
for (int col = colStart; col <= colEnd; col++)
{
allNumbersInSquareArray[counter] = sudoku[row, col];
counter++;
}
}

if (!DoesArrayHaveOnlyOneInstanceOfEachNumber(allNumbersInSquareArray))
return false;

// increment to the next 3*3 square going along horizontally first
if (colEnd != 8)
{
colStart += 3;
colEnd += 3;
}
else // go down to next 'row' of squares
{
colStart = 0;
colEnd = 2;
rowStart += 3;
rowEnd += 3;
}

squareCounter++;
}
return true;
}

Making a Solver

Strategy was to (For all the elements with 0 in them):

  • Get rid of numbers
    • LookAtOtherNumbersInRowAndTakeOutOnesWeDontNeedToCheck
    • LookAtOtherNumbersInColumnAndTakeOutOnesWeDontNeedToCheck
    • LookAtOtherNumbersInSquareAndTakeOutOnesWeDontNeed
    • Then select a random number from the ones left
    • check if sudoku is solved

I used TDD on each Method eg

[TestMethod]
public void LookAtOtherNumbersInRowAndTakeThoseOffTheListOfNumbersToTry()
{
int row = 2;
List<int> listOfNumbersToTry = new List<int>();
for (int i = 1; i < 10; i++)
listOfNumbersToTry.Add(i);

int[,] trySudokuArray = new int[9, 9]{ {1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,0,4,5,6,0,8,0}, // this one
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9}
};
LookAtOtherNumbersInRowAndTakeOutOnesWeDontNeedToCheck(trySudokuArray, row, listOfNumbersToTry);

Assert.AreEqual(3, listOfNumbersToTry.Count);
Assert.IsTrue(listOfNumbersToTry.Contains(3));
Assert.IsTrue(listOfNumbersToTry.Contains(7));
Assert.IsTrue(listOfNumbersToTry.Contains(9));
}

//level 1
public static int[,] solve(int[,] inputSudokuArray) {

// fill in numbers which are correct
//int[,] sudokuArrayAfterB = new int[9, 9];
//sudokuArrayAfterB = solveB(inputSudokuArray);

// semi random code
Random random = new Random();
bool isSolved = false;
int numberOfIterations = 0;

while (!isSolved)
{
int[,] trySudokuArray = (int[,])sudokuArrayAfterB.Clone();
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
if (trySudokuArray[row,col] == 0) // if it is blank
{
// setup numbers to try, then strategy is to take out of this list
List<int> listOfNumbersToTry = new List<int>();
for (int i = 1; i < 10; i++)
listOfNumbersToTry.Add(i);

LookAtOtherNumbersInRowAndTakeOutOnesWeDontNeedToCheck(trySudokuArray, row, listOfNumbersToTry);

LookAtOtherNumbersInColumnAndTakeOutOnesWeDontNeedToCheck(trySudokuArray, col, listOfNumbersToTry);

LookAtOtherNumbersInSquareAndTakeOutOnesWeDontNeed(trySudokuArray, row, col, listOfNumbersToTry);

// are there any possible numbers?
if (listOfNumbersToTry.Count > 0)
{
// pick a random number from listOfNumbersToTry
int indexOfListNumberToGet = random.Next(0, listOfNumbersToTry.Count());
trySudokuArray[row,col] = listOfNumbersToTry[indexOfListNumberToGet];
}
else
goto Foo;
}
}
}
isSolved = checkSudoku(trySudokuArray);

if (isSolved)
{
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
Debug.Write(trySudokuArray[row, col] + " ");
Debug.WriteLine("");
}
return trySudokuArray;
}
Foo:
if (numberOfIterations % 1000 == 0)
Debug.WriteLine("iterations: " + String.Format("{0:0,0}",numberOfIterations));
//Console.WriteLine("iterations: " + String.Format("{0:0,0}", numberOfIterations));
numberOfIterations++;
}
return null;
}

 

StrategyB – Make numbers definite if we know they are

  • For each 0 square see if there is only 1 possible number
    • ie look at LookAtOtherNumbersInRowAndTakeOutOnesWeDontNeedToCheck etc
    • put that number in the square
    • keep looping the whole board until nothing is changed
| | # 
# Monday, 07 March 2011
[TestMethod]
public void UnitTestThings()
{
Thing thing = new Thing();
IEnumerable<Thing> listOfThings = thing.giveMeAllThings();
Assert.AreEqual(3, listOfThings.Count()); // linq count
Assert.IsTrue(listOfThings.Any(t => t.name == "phone" && t.age == 3));
Assert.IsTrue(listOfThings.Any(t => t.name == "waterbottle" && t.age == 2));
Assert.IsTrue(listOfThings.Any(t => t.name == "pinecone" && t.age == 17));
}

Collection assertions http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx

this is different from Contains:

[TestMethod]
public void when_asked_for_all_of_the_movies_it_should_receive_a_set_containing_each_movie_in_the_library()
{
Movie first_movie = new Movie();
Movie second_movie = new Movie();
movie_collection.Add(first_movie);
movie_collection.Add(second_movie);

MovieLibrary movieLibrary = new MovieLibrary(movie_collection);

IEnumerable<Movie> all_movies = movieLibrary.all_movies();

Assert.IsTrue(all_movies.Contains(first_movie));
Assert.IsTrue(all_movies.Contains(second_movie));
}

| | # 
[TestMethod]
public void when_sorting_movies_it_should_be_able_to_sort_all_movies_by_title_descending()
{
populateTestMovies(movie_collection);
MovieLibrary movieLibrary = new MovieLibrary(movie_collection);
IEnumerable<Movie> results = movieLibrary.sort_all_movies_by_title_descending();

IEnumerable<string> expected = new[]
{
theres_something_about_mary.title,
the_ring.title,
shrek.title,
pirates_of_the_carribean.title,
indiana_jones_and_the_temple_of_doom.title,
cars.title,
a_bugs_life.title
};
Assert.IsTrue(results.Select(m => m.title).SequenceEqual(expected));
}

thanks to http://stackoverflow.com/questions/5218505/assert-that-a-collection-is-in-the-right-order

| | # 
[TestMethod]
public void when_adding_two_different_copies_of_the_same_movie_it_should_store_only_1_copy_in_the_collection()
{
MovieLibrary movieLibrary = new MovieLibrary(movie_collection);
Movie speed_racer = new Movie { title = "Speed Racer" };
Movie another_copy_of_speed_racer = new Movie { title = "Speed Racer" };

movieLibrary.add(speed_racer);
movieLibrary.add(another_copy_of_speed_racer);

Assert.AreEqual(1, movie_collection.Count);
}
 
Here is MovieLibrary:
public void add(Movie movie)
{
// .Contains is from List
// Actually uses .Equals method to see if any movies in collection is .Equal to the new one
if (!_list_of_movies_passed_to_us.Contains(movie))
_list_of_movies_passed_to_us.Add(movie);
}

And here is Movie, with the shorter way commented out with a longer way working

public class Movie : IEquatable<Movie>
{
// Properties
public string title { get; set; }
public ProductionStudio production_studio { get; set; }
public Genre genre { get; set; }
public int rating { get; set; }
public DateTime date_published { get; set; }

// Method
public bool Equals(Movie other)
{
//return other == null ? false : other.title == this.title;
if (other == null)
return false;
else if (other.title == this.title)
return true;
else
return false;
}
}

| | # 

http://stackoverflow.com/questions/3686739/what-does-return-type-of-icollectionperson-mean

It is often better to return an interface instead of ‘concrete’ class (or implementation).

The reason for this is the freedom it provides – the implementation may change at a later date without affecting the calling code.

eg giveMeAllThings can change internally as long as I implement the methods that ICollection requires.  And as a List implements these (and more), then this works.

Inside giveMeAllThings, I could have anything I like (doesn’t have to be a List).

public class Thing
{
public string name { get; set; }
public int age { get; set; }

public ICollection<Thing> giveMeAllThings()
{
IList<Thing> listOfThings = new List<Thing>();
Thing thing1 = new Thing { name = "phone", age = 3 };
Thing thing2 = new Thing { name = "waterbottle", age = 2 };
Thing thing3 = new Thing { name = "pinecone", age = 17 };
listOfThings.Add(thing1);
listOfThings.Add(thing2);
listOfThings.Add(thing3);
//foreach (Thing t in listOfThings)
// yield return t;

return listOfThings;
}
}

[TestClass]
public class UnitTest1
{
[TestMethod]
public void UnitTestThings()
{
Thing thing = new Thing();
IEnumerable<Thing> listOfThings = thing.giveMeAllThings();
Assert.AreEqual(3, listOfThings.Count()); // linq count
Assert.IsTrue(listOfThings.Any(t => t.name == "phone" && t.age == 3));
Assert.IsTrue(listOfThings.Any(t => t.name == "waterbottle" && t.age == 2));
Assert.IsTrue(listOfThings.Any(t => t.name == "pinecone" && t.age == 17));
}

[TestMethod]
public void UnitTestThingsWhereNeedAnICollection()
{
Thing thing = new Thing();
ICollection<Thing> listOfThings = thing.giveMeAllThings();
Assert.AreEqual(3, listOfThings.Count); // ICollection count
}

// Won't compile as return type of giveMeAllThings is an ICollection
//[TestMethod]
//public void UnitTestThingsWhereINeedAnActualList()
//{
// Thing thing = new Thing();
// IList<Thing> listOfThings = thing.giveMeAllThings();
// Assert.AreEqual(3, listOfThings.Count); // List count
//}

 

 http://elegantcode.com/2008/04/07/replace-your-collections-with-ienumerablet/

Good article here.. basically saying that he is using IEnumerable<T> mostly, and Linq for things like Count, ElementAt etc..

| | # 
# Friday, 04 March 2011

From http://msdn.microsoft.com/en-us/library/ms173156.aspx

public class Car : IEquatable<Car>
{
public string Make {get; set;}
public string Model { get; set; }
public string Year { get; set; }

// Implementation of IEquatable<T> interface
public bool Equals(Car car)
{
if (this.Make == car.Make &&
this.Model == car.Model &&
this.Year == car.Year)
{
return true;
}
else
return false;
}
}

When a class implements an interface, the class provides an implementation for all the members (properties and methods) defined by the interface

The IEquatable<T> interface announces to the user of the object that the object can determine whether it is equal to other objects of the same type, and the user of the interface does not have to know how this is implemented.

http://www.devarticles.com/c/a/C-Sharp/Interface-IEnumerable-and-IEnumerator-in-C-sharp/1/

What is an interface?
"An interface is a collection of method definitions (without implementations) and constant values".

Its purpose is to captures similarities between unrelated classes without forcing a class relationship,

IEnumerable and IEnumerator are the best interface examples there are for you to understand the role of interface. Classes implementing these two interfaces are classified as an enumerable collection. This means that class behaves like any other collection object written by Microsoft, such as an ArrayList.

There are many features that define an enumerable collection, and by implementing these two interfaces, the framework guarantees that this object has these features. For example, an enumerable collection must have a method called MoveNext, which moves the cursor within the collection one step forward. By implementing the IEnumerator interface, the class is promising (and is required) to implement this method.

As mentioned above, when a class implements these interfaces and is defined as an enumerable collection, it behaves like one as well. This means that it is capable of being iterated using a foreach statement, just like we can do with an ArrayList object.

Programming to an Interface

http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface

common traits or behaviors that were exhibited by potentially many non-related classes of objects

| | # 
# Thursday, 03 March 2011

“..enums a great way to declare a variable of a type that can be one of a fixed set of values.”

http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/08/c-fundamentals-the-joys-and-pitfalls-of-enums.aspx

public enum ProductionStudio { MGM, Paramount, Universal, Pixar, Disney, Dreamworks};


public class ProductionStudio
{
public static readonly ProductionStudio MGM = new ProductionStudio();
public static readonly ProductionStudio Paramount = new ProductionStudio();
public static readonly ProductionStudio Universal = new ProductionStudio();
public static readonly ProductionStudio Pixar = new ProductionStudio();
public static readonly ProductionStudio Disney = new ProductionStudio();
public static readonly ProductionStudio Dreamworks = new ProductionStudio();
}

In some situations you may want to use public static readonly… a constant really.  Gives intellisense.

| | # 

http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c

public class Movie
{
// this is a field. It is private to your class and stores the actual data.
private string _title;

// this is a public field. Almost never used, as its exposing the internals of the class to the outside world
public string _title;

// this is a property. When you access it uses the underlying field, but only exposes
// the contract that will not be affected by the underlying field
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}

// Auto implemented property in C#3
public string Title1 { get; set; }
}

| | # 
# Thursday, 13 January 2011

From the Guernsey adult literacy project, page 51.

What arithmetical symbols do you have to insert in between the numbers to get the correct result?

1 3 5 7 9 = 3

1 3 5 7 9 = 47

1 3 5 7 9 = 18

Note that only the symbols +, –, * and / are used.

An interesting challenge – do they mean that operator precedence is invoked too?  ie MIDAS – Multiply before divide before add before subtract?

http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx  - order of all operators

image

a very useful sanity check in google..

 

Answers I found are:

-1-3+5-7+9 = (-1) - 3 + 5 - 7 + 9 = 3

1+3*5-7+9 = 1 + (3 * 5) - 7 + 9 = 18
-1*3+5+7+9 = 181 + (3 * 5) - 7 + 9 = 18

1*3+5*7+9 =  (1 * 3) + (5 * 7) + 9 = 47
-1-3*5+7*9 =(-1) - (3 * 5) + (7 * 9) = 47

Code I used is:

string opZ = "";
string opA = "";
string opB = "";
string opC = "";
string opD = "";
for (int h = 1; h <= 2; h++) // making the first number positive or negative
{
if (h == 1) opZ = "";
if (h == 2) opZ = "-";

for (int i = 1; i <= 4; i++)
{
if (i == 1) opA = "*";
if (i == 2) opA = "/";
if (i == 3) opA = "+";
if (i == 4) opA = "-";
for (int j = 1; j <= 4; j++)
{
if (j == 1) opB = "*";
if (j == 2) opB = "/";
if (j == 3) opB = "+";
if (j == 4) opB = "-";
for (int k = 1; k <= 4; k++)
{
if (k == 1) opC = "*";
if (k == 2) opC = "/";
if (k == 3) opC = "+";
if (k == 4) opC = "-";
for (int l = 1; l <= 4; l++)
{
if (l == 1) opD = "*";
if (l == 2) opD = "/";
if (l == 3) opD = "+";
if (l == 4) opD = "-";
string expression = opZ + 1 + opA + 3 + opB + 5 + opC + 7 + opD + 9;
DataTable dummy = new DataTable();
double result = Convert.ToDouble(dummy.Compute(expression, string.Empty));
if (result == 3)
Debug.WriteLine(expression + " = 3");

if (result == 47)
Debug.WriteLine(expression + " = 47");

if (result == 18)
Debug.WriteLine(expression + " = 18");

}
}
}
}
}

thanks to http://stackoverflow.com/questions/174664/operators-as-strings for the DataTable help.

From http://stackoverflow.com/questions/4679056/code-smell-in-dynamic-expression

TDD

To help in the refactoring I used tests to make sure I hadn’t broken anything:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Diagnostics;

namespace Guernsey1
{
/// <summary>
/// What arithmetical symbols do you have to insert in between the numbers to get the correct result?
/// 1 3 5 7 9 = 3
/// 1 3 5 7 9 = 47
/// 1 3 5 7 9 = 18
/// There may be more than one answer for each one.
/// </summary>
[TestClass]
public class UnitTest1
{
[TestMethod]
public void GetAnswersForResultIs3()
{
List<string> listOfExpressions = findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(3);
foreach (string expression in listOfExpressions)
Assert.AreEqual("-1-3+5-7+9", expression);
}

[TestMethod]
public void GetAnswersForResultIs47()
{
List<string> listOfExpressions = findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(47);
Assert.AreEqual(true, listOfExpressions.Contains("1*3+5*7+9"));
Assert.AreEqual(true, listOfExpressions.Contains("-1-3*5+7*9"));
}

[TestMethod]
public void GetAnswersForResultIs18()
{
List<string> listOfExpressions = findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(18);
Assert.AreEqual(true, listOfExpressions.Contains("-1*3+5+7+9"));
Assert.AreEqual(true, listOfExpressions.Contains("1+3*5-7+9"));
}



public List<string> findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(int resultExpected) // Jons
{
List<string> listOfExpressions = new List<string>();
string[] prefixes = { "", "-" };
string[] operators = { "*", "/", "+", "-" };
IEnumerable<string> expressions = from prefix in prefixes
from opA in operators
from opB in operators
from opC in operators
from opD in operators
select prefix + 1 + opA + 3 + opB + 5 + opC + 7 + opD + 9;

foreach (string expression in expressions)
{
DataTable dummy = new DataTable();
double result = Convert.ToDouble(dummy.Compute(expression, string.Empty));
if (result == resultExpected)
listOfExpressions.Add(expression);
}
return listOfExpressions;
}

public List<string> findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(int resultExpected) // Cines
{
string[] prefixes = { "", "-" };
string[] operators = { "*", "/", "+", "-" };
List<string> listOfExpressions = new List<string>();
foreach (string opA in operators)
foreach (string opB in operators)
foreach (string opC in operators)
foreach (string opD in operators)
foreach (string prefix in prefixes)
{
string expression = prefix + 1 + opA + 3 + opB + 5 + opC + 7 + opD + 9;
DataTable dummy = new DataTable();
double result = Convert.ToDouble(dummy.Compute(expression, string.Empty));
if (result == resultExpected)
listOfExpressions.Add(expression);
}
return listOfExpressions;
}


public List<string> findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(int resultExpected) // Anton1
{
List<string> listOfExpressions = new List<string>();
var calculator = new DataTable();
var operators = "*/+-";
for (int i = 0; i < 0x200; ++i)
{
string expression = String.Format("{0}1{1}3{2}5{3}7{4}9",
(i & 0x100) != 0 ? "-" : "",
operators[(i >> 0) & 3],
operators[(i >> 2) & 3],
operators[(i >> 4) & 3],
operators[(i >> 6) & 3]);

var result = calculator.Compute(expression, String.Empty);
if (Convert.ToDouble(result) == resultExpected)
listOfExpressions.Add(expression);
}
return listOfExpressions;
}

public List<string> findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(int resultExpected) // Anton2 - not working yet.. how to get the listOfExpressions?
{
List<string> listOfExpressions = new List<string>();
var operators = new Func<int, int, int>[] {
(a, b) => a + b,
(a, b) => a - b,
(a, b) => a * b,
(a, b) => a / b
};

for (int i = 0; i < 0x200; ++i)
{
var stack = 0; // max stack depth is 2 because only 2 priorities
var last = 0; // imitate + for lowest precedence
var value = (i & 0x100) != 0 ? -1 : 1;

for (int j = 0; j < 5; ++j) // extra item to force last reduction
{
var oper = (i >> j * 2) & 3; // "input" operator
if (oper / 2 <= last / 2) // reduce?
{
stack = operators[last](stack, value);
}
else // stack is empty; prepare to shift
stack = value;

if (j == 4) break;

last = oper; // shift operator
value = 3 + j * 2; // "input" number
}
}
// result in stack

return listOfExpressions;
}
}
}

| | # 
# Saturday, 11 December 2010

Lambda expressions are a simpler syntax for anonymous delegates

// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();

// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();

I think this is clearer:

// anonymous delegate
IEnumerable<int> evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList(); // forcers immediate query evaluation

Many thanks to http://stackoverflow.com/questions/167343/c-lambda-expression-why-should-i-use-this

| | # 
# Wednesday, 08 December 2010
( c# language | Euler | Linq )

This is a fun site:

http://projecteuler.net

The first problem is:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

static void Main(string[] args)
{
int overallSum = 0;
for (int i = 1; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
overallSum += i;
}
Console.WriteLine("overall sum is: " + overallSum.ToString());
Console.ReadLine();
}
// should be 233168

or Phils way:

//Find the sum of all the multiples of 3 or 5 below 1000.
//There is a summation formula which states
//The sum of all numbers from i = 1 to i = n is n(n+1)/2
static void Main(string[] args)
{
int total = (3 * Convert.ToInt32(999 / 3) * (Convert.ToInt32((999 / 3)) + 1)) / 2
+ (5 * Convert.ToInt32(999 / 5) * (Convert.ToInt32((999 / 5)) + 1)) / 2
- (15 * Convert.ToInt32(999 / 15) * (Convert.ToInt32((999 / 15)) + 1)) / 2;

Console.WriteLine("overall sum is: " + total.ToString());
Console.ReadLine();

}

from http://answers.yahoo.com/question/index?qid=20100422031504AAfmpJ5)

or Simons way using method syntax (or fluent)

int result = Enumerable.Range(0, 1000)  // generates a sequence of numbers in a range
.Where(i => i % 3 == 0 || i % 5 == 0) // filter using lambda expression
.Sum(); // sum of int32 using extension methods


and for fun, using method and query syntax
 
// get the ones divisible by 3 in the list - Method syntax
IEnumerable<int> listOfDivisibleBy3Method = listOfInts
.Where(i => i % 3 == 0);

// get the ones divisible by 3 in the list - Query syntax
IEnumerable<int> listOfDivisibleBy3Query = from number in listOfInts
where (number % 3 == 0)
select number;

http://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression

| | # 
# Thursday, 18 November 2010

something like:

Array arraything = "abc, def";

           foreach (var item in arrayThing)
           {
               Console.WriteLine("item is: " + item);
           }

 

This works becuase an array in enumerable

| | # 
# Wednesday, 17 November 2010
DateTime EffectiveDate;
if (!DateTime.TryParse(cert.GetEffectiveDateString(), out EffectiveDate))
{
return false;
}

| | # 
# Saturday, 25 September 2010

I saw some interesting code:

for (; contours != null; contours = contours.HNext)
{
Contour<Point> approxContour = contours.ApproxPoly(contours.Perimeter * 0.02, contours.Storage);
img.Draw(approxContour, new Bgr(1, 1, 251), 2);
}

I’d never seen the initial part of the for statement missing so I played:

class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++) // normal usage
{
Console.WriteLine("i count is {0}", i);
}

int k = 1;
for (; k<=5; k++) // missing first bit
{
Console.WriteLine("k count is {0}", k);
}

int m = 1;
for (; m <= 5;) // missing last bit too
{
Console.WriteLine("m count is {0}", m);
m++;
}

for (; ; ) // infinite loop, never breaks out
{

}



Contour contA = new Contour { x = 10, y = 20 };
Contour contB = new Contour { x = 50, y = 60 };
Contour contC = new Contour { x = 90, y = 100 };

List<Contour> listOfContours = new List<Contour>();
listOfContours.Add(contA); // better way to add to a collection?
listOfContours.Add(contB);
listOfContours.Add(contC);

foreach (Contour contour in listOfContours)
{
Console.WriteLine("x is {0}", contour.x.ToString());
Console.WriteLine("y is {0}", contour.y.ToString());
Console.WriteLine();
}

int j = 0;
while (j < 5)
{
Console.WriteLine("While loop counter is {0}", j.ToString());
j++;
}
}
}

class Contour
{
public int x;
public int y;
//public int x { get; set; }
//public int y { get; set; }
}


| | # 
# Thursday, 05 August 2010

I’m getting data using LINQ to SQL, then showing on the front end.  If I want a null coming from the database to default to something:

<telerik:GridTemplateColumn HeaderText="Image" UniqueName="Image">  
<ItemTemplate>
<asp:Label ID="asdf" runat="server" Text='<%# String.IsNullOrEmpty(Convert.ToString(Eval("Image1"))) ? "noImage.jpg" : Eval("Image1")%>'></asp:Label>
<a href="<%=VirtualPathUtility.ToAbsolute("~/")%>showFrontEndMaterialDetail.aspx?materialId=<%# Eval("Id")%>">
<img src="<%=VirtualPathUtility.ToAbsolute("~/")%>Images/Uploaded/Thumbs/<%# Eval("Image1") ?? "noPhoto.jpg" %>"></img></a>

</ItemTemplate>
</telerik:GridTemplateColumn>


Thanks to these people:
 

http://stackoverflow.com/questions/3410942/linq-to-sql-default-value-nullable

| | # 

When displaying a repeater on an aspx page:

<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "FileName")%>
</ItemTemplate>
</asp:Repeater>

or shorter:

<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%#Eval("FileName")%>
</ItemTemplate>
</asp:Repeater>

It is important to remember to make FileName a property and not just a public field ie this works

public class ImageThing
{
public string FileName {get; set; }
}

private void DisplayThumbnailImages()
{
ImageThing imageThing1 = new ImageThing();
ImageThing imageThing2 = new ImageThing();
imageThing1.FileName = "asdf.jpg";
imageThing2.FileName = "aaa.jpg";

List<ImageThing> imagesToRender = new List<ImageThing>();
imagesToRender.Add(imageThing1);
imagesToRender.Add(imageThing2);

Repeater1.DataSource = imagesToRender;
Repeater1.DataBind();
}

this doesn’t

public class ImageThing
{
public string FileName;
}

A property encapsulates a field.

| | # 
# Wednesday, 23 June 2010

While trying to figure out what is meant by the 3rd new section in a view in MVC

<%: Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) %>

So it is really creating an object with a single property id, which is an int, equal to that of the item, which is a Dinner.

image

“Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type”

class Program
{
static void Main(string[] args)
{
// Anonymous types provide a convenient way to encapsulate a set of read-only properties
// into a single object without having to first explicitly define a type
var person = new { Name = "Terry", Age = 21 };
Console.WriteLine("name is " + person.Name);
Console.WriteLine("age is " + person.Age.ToString());

// Anonymous types just get rid of Person1 really.
Person1 person1 = new Person1 { Name = "Bill", Age = 55 };
Console.WriteLine("name is " + person1.Name);
Console.WriteLine("age is " + person1.Age.ToString());
}
}

class Person1
{
public string Name { get; set; }
public int Age { get; set; }
}

Many thanks to the question here for clarifying:
 
| | # 
# Thursday, 11 February 2010

Static classes are usually used as ‘utility’ classes

You don’t need an instance

 

class Program
{
static void Main()
{
double result = thing.daveSubtract(10);
Console.WriteLine(result);
}
}

static class thing
{
static public double daveSubtract(double number)
{
return (number - 2);
}
}

Extension Methods

From: http://msdn.microsoft.com/en-us/library/bb383977.aspx

Extension methods enable you to "add" methods to existing types without creating a new derived type,

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

For client code, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

 

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "hello extension methods are good";
Console.WriteLine(s);
int i = s.WordCount();
Console.WriteLine("number of words is {0}", i.ToString());
}
}

public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

| | #