ISourceCode

Make the frequent cases fast and the rare case correct

Monthly Archives: January 2012

Using Regex to solve Diophantine equations – Perl

I stumbled upon this cool concept of solving algebraic equations especially the tougher Diophantine equation using regex.

I decided to aggregate the information i found into this article and its worth to know this super cool concept.

You can find a nice introduction about solving algebra equations using regex in this blog post by author of regex cookbook.

Diophantine equation is an indeterminate polynomial equation that allows the variables to be integers only. Diophantine problems have fewer equations than unknown variables and involve finding integers that work correctly for all equations – Wikipedia.

The Oldest plays piano puzzle ends up being a Diophantine equation. In the perl monks you can see how the author uses regex to derive the different possible solutions to x*y*z = 72 equation and hence find a solution to the puzzle.

However this could only work for positive integers and a positive constant as described in this forum.

But if you know before hand that your variables and constant need to be positive for example the piano puzzle( the ages cant be negative) its worthwhile to use a regex to get those values.

#!/usr/bin/perl
# 3x + 2y + 5z = 40
$_ = 'o' x 40;
$a = 'o' x 3;
$b = 'o' x 2;
$c = 'o' x 5;
$_ =~ /^((?:$a)+)((?:$b)+)((?:$c)+)$/;
print "x = ", length($1)/length($a), "\n";
print "y = ", length($2)/length($b), "\n";
print "z = ", length($3)/length($c), "\n";

OUTPUT:

> perl darkmoon.pl
x = 11
y = 1
z = 1

C# – Delegate Covariance and Contravariance

In Computer Science within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations (such as parameters, generics, and return types). – Wikipedia

Thus,
covariant: converting from wider (double) to narrower (float).
contravariant: converting from narrower (float) to wider (double).

In C# 2.0 covariance and contravariance was introduced for delegates. Method group to delegate conversions are covariant in return types, and contravariant in argument types – msdn FAQ

In the previous article delegates in C# were explained. How they are declared, instantiated and invoked was explained. In the article it was mentioned that the method’s argument types and return type should match the delegate’s argument types and return types. However this rule can be made flexible by use of Covariance and Contravariance.

To begin with there is a base class Planet with a method CallingPlanet() and derived class Earth with a method CallingEarth()/

In Covariance a method can be encapsulated who’s return type is directly or indirectly derived from return type of delegate.

For example

public delegate Planet CovariantDelegate( );

is a covariant delegate with return type Planet. Thus methods CallingPlanet() and CallingEarth() are encapsulated by the delegate and the return type of these methods are either of type Planet or a derived type from Planet i.e Earth. So methods returning Planet and Earth can be reference by the covariant delegate who’s return type is of the base class type i.e Planet.

In Contravariance for example a delegate

public delegate void ContravariantDelegate(Earth objEarth);

can be defined to take a method who’s parameter is Earth. If Earth derives from Planet then the delegate can encapsulate a method PlanetParamMethod(Planet objPlanet) that take Planet object as parameter. So if a delegate take a parameter of a derived type then we can use this delegate to reference a method that takes base class type as parameter. Thus enabling to call both methods one with base type parameter and the other with derived type parameter.

invocation can be done like this

ContravariantDelegate varContravariantDelegate = new ContravariantDelegate(PlanetParamMethod);
varContravariantDelegate(e);

varContravariantDelegate = new ContravariantDelegate(EarthParamMethod);
varContravariantDelegate(e);

where e is the Earth object and referenced methods are PlanetParamMethod(Planet objPlanet) and EarthParamMethod(Earth objEarth)


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

namespace Co_ContravarianceDemo
{
    class Planet
    {
        public Planet CallingPlanet( )
        {
            Console.WriteLine("Displaying a planet base class");
            return this;
        }
    }
    class Earth : Planet
    {
        public Earth CallingEarth( )
        {
            Console.WriteLine("Displaying earth derived class");
            return this;
        }
    }
    class Program
    {
        public delegate Planet CovariantDelegate( );
        public delegate void ContravariantDelegate(Earth objEarth);

        private static void PlanetParamMethod(Planet objPlanet)
        {
            Console.WriteLine("Method for Planet object");
        }

        private static void EarthParamMethod(Earth objEarth)
        {
            Console.WriteLine("Method for Earth object");
        }

        static void Main(string[ ] args)
        {
            Planet p = new Planet( );
            Earth e = new Earth( );

            CovariantDelegate varCovariantDelegate = new CovariantDelegate(p.CallingPlanet);
            varCovariantDelegate( );

            varCovariantDelegate = new CovariantDelegate(e.CallingEarth);
            varCovariantDelegate( );

            ContravariantDelegate varContravariantDelegate = new ContravariantDelegate(PlanetParamMethod);
            varContravariantDelegate(e);

            varContravariantDelegate = new ContravariantDelegate(EarthParamMethod);
            varContravariantDelegate(e);
        }
    }
}

OUTPUT:

\bin\Debug> .\Co_ContravarianceDemo.exe
Displaying a planet base class
Displaying earth derived class
Method for Planet object
Method for Earth object

Thus summarizing as per the MSDN FAQ
When you instantiate a delegate Planet CovariantDelegate( ), you can assign it a method CallingEarth( )that has a more derived (Earth) return type than that specified in the delegate (Planet) – (covariance).

You can also assign a method PlanetParamMethod(Planet objPlanet) that has parameter types of base type (Planet objPlanet) which is less derived or parent type than those in the delegate (Earth theEarth), hence we can pass an object of the base type as a parameter where an object of derived type is expected.-(contravariance).

C# example – (Single & Multicast) Delegate objects referencing named & anonymous methods.

The delegate keyword is used to declare a reference type that can be used to encapsulate a named or an anonymous method. – msdn.

Delegates are similar to function pointers in C++. Delegates are type safe something you would expect from a type safe language as C#. A delegate lets you pass a function as a parameter and is type safe since the function you pass as a delegate will have the same signature as the delegate declaration. Delegate types are sealed.In this article we can see how a delegate can be instantiated by associating it either with a named or anonymous method. Delegates are immutable.

I strongly recommend reading the code and understand how it works before absorbing the theory behind it. sometimes all the terminologies can get complicated but the code looks fairly simple and self understandable.

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

namespace DelegatesDemo
{
    public delegate void Calculate(int x, int y);

    class Program
    {
        // Add method associated with the named delegate Calculate:
        // Add is instance method:
        public void Add(int x, int y)
        {
            int result = x + y;
            System.Console.WriteLine(" Addition : {0}", result);
        }
        // Sub method associated with the named delegate Calculate:
        // Sub is a static method
        public static void Sub(int x, int y)
        {
            int result = x - y;
            System.Console.WriteLine(" Subtraction : {0}", result);
        }

        static void Main()
        {
            Calculate a, b, c, d;

            // delegate object a referencing Add
            // The delegate instantiation using a named method Add
            // delegate mapped to instance method.
            Program pgm = new Program();
            // if you do not create a object of class to map the instance method it throws 
            // An object reference is required for the nonstatic field error.
            a = pgm.Add;

            // delegate object b that references Sub
            // delegate mapped to static method
            b = Sub;

            // Multicast delegate c two composed of a and b 
            c = a + b;

            // adding delegate b to c to call method Sub twice
            d = c + b;

            System.Console.WriteLine("Invoking named single delegate a:");
            // The delegate instantiation using a named method
            a(20,10);
            System.Console.WriteLine("Invoking named single delegate b:");
            b(20,10);
            System.Console.WriteLine("Invoking named multicast delegate c:");
            c(20,10);
            System.Console.WriteLine("Invoking named multicast delegate d:");
            d(20,10);

            // from composed delegate d remove b which calls only the method Add
            d = c - b;
            System.Console.WriteLine("Invoking name multicast delegate d after new reference:");
            d(20, 10);

            // Instatiate the delegate type using an anonymous method:
            System.Console.WriteLine("Invoking Anonymous delegate");
            Calculate p = delegate(int x, int y)
            {
                int result = x * y;
                System.Console.WriteLine(" Multiplication by anonymous method : {0}", result);
            };

            // anonymous delegate call which results in a multiplication
            p(30,40);
        }
    }
}

OUTPUT:

DelegatesDemo.exe
Invoking named single delegate a:
Addition : 30
Invoking named single delegate b:
Subtraction : 10
Invoking named multicast delegate c:
Addition : 30
Subtraction : 10
Invoking named multicast delegate d:
Addition : 30
Subtraction : 10
Subtraction : 10
Invoking name multicast delegate d after new reference:
Addition : 30
Invoking Anonymous delegate
Multiplication by anonymous method : 1200

generic delegates (not covered in this article) can also be created to define its own type parameters.

Using a delegate involves declaring, instantiating and calling it.
Following is the declaration of a delegate in the program.

public delegate void Calculate(int x, int y);

A delegate is derived from an abstract class called System.MulticastDelegate which is inherited from System.delegate abstract class. – msdn

A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. – msdn . In the code you can see delegates mapped to both static and instance methods.

Named & anonymous methods – A delegate is ideal for anonymous invocation since a method’s argument types and return type match the delegate’s argument types and return types, although this is flexible with use of covariance/contravariance. Code shows how a delegate can make reference to a named and anonymous methods. The named method can be either static or an instance method. Sometimes for example in threading creating a new method is undesirable and hence a code block can be defined immediately for a delegate to process this was introduced in C# 2.0 version. Code shows how anonymous method can be used.

Single & composing Multicast Delegate – apart from mapping a single delegate to a method. we can assign delegate objects in such a way that the delegate instance can multicast using the + operator. the delegate is thus composed of many delegates. The delegate calls the sub delegates it was composed from in a sequential order for example a delegate d = c + b calls method mapped by c and then b. Only delegates of the same type can be composed. Thus, remember multicast(composed) delegate holds the reference of more than one method. This multicast delegate stores all reference as linked list. All functions will call in sequence as they are assigned. Similarly the – operator can be used to remove a component delegate from a composed delegate.

Why Delegates?

Delegates are perfect for use as events.
delegates can be used to make asynchronous callbacks.

This leaves me with further work to write articles that answer these questions?

Use of delegates as events?
asynchronous callbacks and their use?

This article represents best of my understanding of delegates and related concepts from the internet resources. Any corrections are welcome.

C# – Virtual Functions/methods vs Abstract functions/methods – (Polymorphism at work)

This article covers the fundamental object oriented concept of virtual function/method and also explain how it differs from abstract methods defined in abstract classes.

Polymorphism enables a derived class to override the behavior of a method of the base class. So many objects of different types can access same methods.

The following code shows how a method Blogger is overridden by a derived class to provide its own functionality. Also if a derived chooses not to override the virtual function and if a call is made then the base class method is executed.

Here is some insight into how a virtual function is different from an abstract method(of an abstract class).

A virtual function can exist in a abstract class or a normal class, while a abstract method exists in a abstract by using the ‘abstract’ keyword. An abstract class can provide complete, default code and/or just the details that have to be overridden. If a derived class inherits from an abstract class then it must provide an overriden implementation for the abstract method, however if a derived class inherits from a base class with a virtual function it does not require to implement it (for example derived2 class below). YOU MUST override a abstract method. So all abstract methods are virtual in the sense that they have to be overriden by the inheritor.


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

namespace VirtualFunction
{
    class Base
    {
        //virtual method in the base class.  
        public virtual void Blogger()
        {
            Console.WriteLine("This is a Base Class blogger");
        }
    }

    class Derived1 : Base
    {
        // Override Blogger()  
        public override void Blogger()
        {
            Console.WriteLine("This is derived1 class blogger");
        }
    }

    class Derived2 : Base
    {
        // This class does not override Blogger(). 
    }

    class Program
    {
        public static void Main()
        {
            Base objBase = new Base();
            Derived1 objDerived1 = new Derived1();
            Derived2 objDerived2 = new Derived2();

            Base identify; // a reference to base class

            identify = objBase;
            identify.Blogger();

            identify = objDerived1;
            identify.Blogger();

            identify = objDerived2;
            identify.Blogger(); // since Blogger is not overriden, base class blogger is called 
        }
    }
}

OUTPUT:

lFunction\VirtualFunction\bin\Debug>VirtualFunction.exe
This is a Base Class blogger
This is derived1 class blogger
This is a Base Class blogger

You can find the C++ version article here

C# – an example to illustrate Mutiple Inheritance through interfaces

A new year and a new post. Some of the readers might find me coding in C# and Python depending on my mood. Here is an example to show how to use interfaces in your C# program. This also shows multiple inheritance that can be achieved through interfaces.

using System;

interface GetSum
{
    int GetSum();
}
interface CalcSum
{
    void CalcSum(int x,int y);
}

namespace MultiInterface
{
    class Addition : GetSum, CalcSum
    {
        int sum;
        public int GetSum()
        {
            return sum;
        }
        public void CalcSum(int x, int y)
        {
            sum = x + y;
        }
    }

    class Program
    {
        static void Main()
        {
            Addition objAdd = new Addition();

            objAdd.CalcSum(8000,200);
            Console.WriteLine("The Sum is = {0}", objAdd.GetSum());
        }
    }
}

OUTPUT:

nterface\MultiInterface\bin\Debug>MultiInterface.exe
The Sum is = 8200

Follow

Get every new post delivered to your Inbox.