Wednesday, November 24, 2010

Sudoku Validation

In one of the interviews I gave recently, there was a question about sudoku validation (9x9). The logic to check itself is quiet simple -
  1. Check for existing value in row
  2. Check for existing value in column
  3. Check for existing value in block

Solution
Two dimensional array is a good data structure to use for it. My first solution involved using three loops but on refinement I was able to use only one loop for the validation. I find the start of block location first. In the loop checking row and column is quite straight forward. It is checking for value in a block that is a bit tricky and I had to play with LinqPad and Excel before I came up with correct statements.

public static bool Validate(int number, int row, int col)
{
    Console.WriteLine("Writing at pos {0},{1} - value {2}", row - 1, col - 1, number);

    var startBlockX = ((row - 1) / 3) * 3;
    var startBlockY = ((col - 1) / 3) * 3;

    for (int i = 0; i < 9; i++)
    {
        if (arr[i, col - 1] == number)
        {
            Console.WriteLine("found in col value {0}", arr[i, col - 1]);
            return false;
        }

        if (arr[row - 1, i] == number)
        {
            Console.WriteLine("found in row value {0}", arr[row - 1, i]);
            return false;
        }

        var mx = (i / 3) + startBlockX;
        var my = startBlockY + (i % 3);
        Console.WriteLine("block pos {0},{1}", mx, my);

        if (arr[mx, my] == number)
        {
            Console.WriteLine("found in block");
            return false;
        }
    }

    return true;
}

Checking
Using the following array and checking for highlighted spots in figure above for value of 9.

var arr = new int[9, 9];

arr[3, 6] = 9;
arr[3, 8] = 7;
arr[0, 8] = 9;
arr[1, 2] = 2;
arr[7, 7] = 9;
Validate(9, 3, 3);
Checking for pos 2,2 - value 9
found in block

Validate(9, 1, 5);
Checking for pos 0,4 - value 9
found in row

Validate(9, 3, 9);
Checking for pos 2,8 - value 9
found in col

Wednesday, November 17, 2010

SSW Sydney .Net User Group Meet

I just attended SSW Sydney .Net User group meet yesterday for the first time and thought would share a summary. The session was attended by a good crowd of about 50 people. Adam Cogan started the meeting with some industry news. The following wsj article "What They Know" was interesting and informative in showing how much of user tracking is being done even by some of the well respected brands.

The first talk was by Peter Gfader. It was good to see him explain object oriented principles and explain about SOLID which I have blogged about earlier. I had knowledge of Broken Window Theory but Boy Scout Rule was new to me and it was interesting. Peter also showed some examples of bad code and we could relate to it in our works. However because of time constraints he had to rush through showing tools like StyleCop, Code Analysis etc. which was a bit unfortunate. His blog post and presentation slides are available here.

The second talk was by TJ Gokcen and he created an apple iphone application using Monotouch. It was great to see a whole new application being developed using language we know pretty well. But I wonder how complicated native applications we can develop with that. I guess mostly sort of web applications which uses web browser but not heavy apps like games etc. The demonstration itself was very informative and I feel comfortable if I have to develop applications like that in iPhone.

Lastly, it was nice talking to people. I couldn't interact much because of my neck pain but it was good to see and listen to different developers. One gentleman I was talking to mentioned the difference between knowledge of a domain expert and coder and how he would rather teach a domain expert some coding than a coder some domain knowledge. I kind of disagree but that is for some other post. I will update this post with link to TJ's slides and code when it is available.

Takeaways

  • The Broken Window Theory
  • The Boy Scout Rule
  • SOLID Principles
  • StyleCop, Code Analysis
  • MonoTouch
  • Feature Pack 2
  • WSJ article "What They Know"
  • C# 5 CTP
  • Windows 7

Tuesday, November 16, 2010

Firefox Extensions for Web Developers 2010

Even though I use Google Chrome as my primary browser, Firefox is my browser of choice for web development - thanks to its wonderful extensions. This post will be useful to you if you are new to web development and want to know some of the best firefox extensions for web development. 

All the recommended extensions on this page are available in one place as a collection - Devnetfx Web Development

If you are short of time, you need to know just the following two extensions and you will be fine for 90% of your development - Firebug and Web Developer

Web Developer - Web Developer is the plugin of choice for style gurus. The toolbar gives you a lot of options for inspecting, validating and optimizing web-pages. 



Firebug - If Web Developer is the tool of choice for style gurus, Firebug is the tool of choice for back-end developers. It becomes a must when you are doing Ajax debugging. It allows editing, debugging, monitoring CSS, HTML, and JavaScript. Firebug is powerful by itself, but when you add other extensions like YSlow, XRefresh, Firecookie etc., it is unbeatable.


Other Extensions


View Source Chart - I love this extension because it allows you to see DOM structure visually.

MeasureIt - This extension sits in one corner and its when I need to check height and width that I call my friend.

ColorZilla is just like MeasureIt - does its job well and quickly. It is Advanced Eyedropper, ColorPicker, Page Zoomer.

iMacros For Firefox - Allows you to automate Firefox. Record and replay repetitious work. Recently I was doing some artwork uploading at a client which involved a combination of UI steps. Thank God I knew about iMacros for Firefox!

Html Validator adds adds HTML validation inside Firefox. The number of errors of a HTML page is seen on the form of an icon in the status bar when browsing.

YSlow analyzes web pages and why they're slow based on Yahoo!'s rules for high performance web sites. PageSpeed from Google is another one which does the same job of analyzing web pages for performance issues.

FireShot creates screenshots of web pages (entirely or just visible part). I just use the basic version and it does my need for taking snapshots easily.

XRefresh does the job of browser refresh for web developers (integrated into Firebug) You need to download software from binaryage to use it. With most developers using two monitors, it becomes an essential utility to see results instantly.

Dummy Lipsum generates "Lorem Ipsum" dummy text from http://www.lipsum.com.

Firesizer allows you to resize the window to specific dimensions - quickly.

X-Ray When I am too lazy to inspect using Firebug and Web Developer, X-Ray allows me to analyze page quickly.

Notable Omissions -
GreaseMonkey GreaseMonkey is one of the most downloaded extensions and it allows you to customize the way a webpage displays using small bits of JavaScript. Perhaps I will find some scripts to start using it in future.

Resources

The Best 50 Firefox add-ons for Web-developers! has a lot of good suggestion. Apart from XRefresh, View Source Chart, ShowIP it covers a lot of ground.


Firebug Extensions page has a list of extensions for firebug. Some firebug extensions are situation specific like FirePyhton, ColdFire etc. and some are generic which can be used in most cases like YSlow, FireFinder etc. I would recommend you to have a look and see if you can find some that meets your needs.

All the recommended extensions on this page are available in one place as a collection - Devnetfx Web Development. I hope you found some useful extension which will make your life easier as a developer.


Sunday, November 14, 2010

ReSharper For Fluent Development

Tools like Resharper and CodeRush are time savers and a must for fluent development. As they tend to overlap, I settled for Resharper just because of familiarity, though as the following poll shows they pretty much evenly balanced. However both of these has a learning curve and you need to learn few more shortcuts to be effective.

Import Symbol
It is a common to inherit from a class or  use a type which is in other projects and you need to import them before you can use them. In ReSharper there is Import Symbol (Shift+Alt+Space) which lets type completion much more easily. It also adds namespace automatically when you select a type.


Tuesday, November 9, 2010

Fixing Code Format

Just noticed that my code examples were not showing properly in Firefox.


The fix was simple. Added the following css property -
white-spacenormal;

However now IE was not happy -


The correct property in this case was -
white-spacepre-wrap;

With “white-space:pre-wrap”, it's like mix of “pre”, and “normal”.
- Repeated spaces are shrinked into just one space.
- Newline char will force a wrap.
- Very long lines will be automatically wrapped too, by the element's width.

I found the information at xahlee useful when fixing this style issue.

Wednesday, November 3, 2010

Covariance and Contravariance in C# 4.0

Variance is about being able to use an object of one type as if it were another, in a type-safe way. Variance comes into play in delegates and interfaces and are not supported for generic and non generic classes.
public class Person {}
public class Customer : Person {}
Covariance is about values being returned from an operation back to the caller. In the following example, the keyword out is used with generic parameter to support covariance. Contravariance is about values being passed in using keyword in.

delegate T MyFunc<out T>(); 

MyFunc<Customer> customer = () => new Customer();

// Converts using covariance - narrower type to wider type assignment 
MyFunc<Person> person = customer; 
delegate void MyAction<in T>(T t);

MyAction<Person> printPerson = (person)=> Console.WriteLine(person);

// converts using contravariance - assignment from a wider type to a narrower type
MyAction<Customer> printCustomer = printPerson;

Tuesday, November 2, 2010

Lets make it SOLID

One unfortunate aspect of working with object-oriented language is that people working with them think they are object oriented programmer just by using C#, Java etc. While design patterns do make you a better object-oriented programmer, they are also hard to learn especially when starting out. It is here that design principles come in handy. And the good thing is once you know design principles, you tend to find design patterns a natural fit into object-oriented programming.

SOLID Design Principles

Single Responsibility Principle (SRP)
SRP states that every object should only have one reason to change and a single focus of responsibility.

Open-Closed Principle (OCP)
A class should be open for extension but closed for modification.

Liskov Substitution Principle (LSP)
You should be able to use any derived class in place of a parent class and have it behave in the same manner without modification.

Interface Segregation Principle (ISP)
Clients should not be forced to depend upon interfaces that they do not use. Make fine grained interfaces that are client specific.

Dependency Inversion Principle (DIP)
Depend on abstractions, not on concrete classes.

Resources

Objectmentor has some good resources on design principles -