Matching two arrays - One Line Beauty ..

24 Jul 2008

Recently I wrote some "useful" code which I would probably release online as an open source; if things do not go as expected. Anyway during that, I had a requirement where I have to match two arrays and return the match %. So let us do it in C# 2.0 or Java for that matter. Look at my code ...

public double match(string[] array1, string[] array2)
{
int common = 0;
foreach(string val1 in array1)
foreach(string val2 in array2)
if(val1.equals(val2)) common++;
double avg = (array1.Length + array2.Length)/2;
return common/avg;
}


Now let us do it in C# 3.0 Way, using extension methods which are already written for us ..

public double match(string[] array1,string[] array2)
{
int common = array1.Where(item=>array2.Contains(item)).Count;
double avg = (array1.Length+array2.Length)/2;
return common/avg;
}


Isn't that sweet? Well, it definitely is sweet. You could do something like that even in Groovy..

public match(array1,array2)
{
def common = array1.find(it->array2.contains(it)).size();
def avg = (array1.length()+array2.length())/2;
return common/avg;
}


Well, the functions size() might either be length() or count() which I usually am confused and since I always an IDE to code, I usually do not take the pain to remember these simple(but important) details. Anyway, if you want to pick the common elements in 10 arrays, even then the code in C# 3.0 or Groovy is going to be 3-4 lines. So it 400% less code?

The point here is that languages are getting sexier with time and it is really fun to write amazingly compact code. For those who haven't tried LINQ, should really take a look at it. By the way, I did a little LINQ to XML and with very little code, it makes using RESTful web services very easy. Hats off! to all the genius who came up with these ideas (of course, Microsoft did not invent closures...)