Pages

Tuesday, November 18, 2008

String combinations using Brute force algorithm.

I have received requests in the past, to post answers for my interview questions (To find my interview questions, search for the tag "interview" in the right side pane under Ram cloud).

I thought let me write this one, string combination. One can find many different implementations through iteration to the permutation and combination of string in the internet.My code below; implements Brute force algorithm to find the string combination and prints them.

[The iterative pattern for the same, is considered to be one of the tough interview questions.]

Language: C#
Compiler: .NET framework 3.5
Platform: Windows server 2008, Intel Core2Duo X64.

// ****************************************************************************
//
// Copyright (C) Global Handler. All rights reserved.
//

// ram@globalhandler.com
//
// This file implements the brute force algorithm to find the string combinations.
// Note: The code is not warranted and not tested.
//

// ****************************************************************************

namespace StringCombination
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

///
/// Functionality to find the string combinations.
///

public class StringCombo
{
#region -= Variables =-

///
/// Dictionary to hold the unique strings.
///

private Dictionary stringDictionary = new Dictionary();

#endregion -= Variables =-

#region -= Constructor =-
///
/// Constructor of
///

/// The input string.
public StringCombo(string givenString)
{
if (String.IsNullOrEmpty(givenString))
{
throw new ArgumentNullException(givenString, "The given string is either Null or Empty");
}

//Find if the given string has unique characters
if (!FindForDuplicatesInString(givenString))
{
throw new ArgumentException("The string contains duplicate characters, please enter a string with unique characters");
}

int dictLimit = FindTheFactorial(givenString.Length);

GetTheCombinationsForAString(givenString, dictLimit);

PrintTheStringCombinations();
}

#endregion -= Constructor =-

#region -= Private Methods =-

///
/// Method to find the unique string combinations.
///

/// The given string.
/// The maximum combinations.
private void GetTheCombinationsForAString(string givenString, int dictionaryLimit)
{
Dictionary dictionaryForControllingRandomValues = null;

do
{
dictionaryForControllingRandomValues = new Dictionary();

do
{
DateTime currentDate = DateTime.Now;

Random rnd = new Random((int)currentDate.Ticks);

int number = rnd.Next(0, givenString.Length); //max number is the input string length.

if (!dictionaryForControllingRandomValues.ContainsKey(number))
{
dictionaryForControllingRandomValues.Add(number, givenString[number]); //char at the given index.
}

//repeats until the count of dict reaches the input string length.
} while (dictionaryForControllingRandomValues.Count != givenString.Length);

StringBuilder sb = new StringBuilder();

foreach(KeyValuePair stringForAddingToMainDict in dictionaryForControllingRandomValues)
{
sb.Append(stringForAddingToMainDict.Value);
}

if (!this.stringDictionary.ContainsKey(sb.ToString()))
{
this.stringDictionary.Add(sb.ToString(), null);
}

//repeats until the string dictionary count reaches the maximum combinations expected.
}while(this.stringDictionary.Count != dictionaryLimit);
}

///
/// Method that finds if the given string contains unique set of characters.
///

/// The given string.
/// Result of evaluation.
private bool FindForDuplicatesInString(string givenString)
{
Dictionary duplicateCharTracker = new Dictionary();

for (int i = 0; i < givenString.Length; i++)
{
char value = givenString[i];

if (duplicateCharTracker.ContainsKey(value))
{
return false;
}
else
{
duplicateCharTracker.Add(value, null);
}
}

return true;
}

///
/// The method that prints the string output.
///

private void PrintTheStringCombinations()
{
foreach (KeyValuePair uniqueString in this.stringDictionary)
{
Console.WriteLine(uniqueString.Key);
}
}

///
/// Method that gets the factorial.
///

/// Lenght of the string.
/// The factorial value.
private int FindTheFactorial(int lengthOfString)
{
if (lengthOfString == 0)
return 0;

int factorial = 1;

for (int i = lengthOfString; i > 1 ; i--)
{
factorial *= i;
}

return factorial;
}
#endregion -= Private Methods =-
}

class Program
{
static void Main(string[] args)
{
StringCombo stringCombo = new StringCombo("abc");

stringCombo = new StringCombo(null);

stringCombo = new StringCombo(string.Empty);

stringCombo = new StringCombo("aaabc");

stringCombo = new StringCombo("12345");
}
}
}


--------------------------------------------------------------------------------
For any questions and comments, please log the comments in the blogpost or alternatively email me at ram@globalhandler.com


Adding the below approach from the comment section:

say you are given a string "abc"

now, make 2 strings (clone and combine & reverse, clone and combine)
abcabc and cbacba
read out them like
abcabc -> abc, bca and cab
cbacba -> cba, bac and acb
combine them
abc bca cab cba bac acb

You know, space is no more a constrain for devs its the parallelism that matters - all that we can do is fork two threads to read them out.

This could very well be tailored using Map/Reduce for large scale clouds and clusters.

Saturday, November 08, 2008

Choosing what you worship

I was confused looking in to the program "god vs Satan" in the History channel, the confusion is that most of the major religions treat snake/serpent as the first incarnation of Satan in this world. But Hinduism treats snake as god, at least a considerable sect of Hindus do so. So is Hinduism a contrast to others?
I was curious to know why is snake worship followed by Hindus?

I started my search in the search engines to get more answers...

And from what I read I was able to deduce that humans tend to submit themselves to the ones that are mightier in some way to them. A snake in nature is poisonous, but humans are forced to live in the same ecosystem as the snake, this creates the classic problem of man vs animal and who survives over the other?. In almost all the cases in the present days we win, but that was not the same in the olden days. So humans developed a habit of pleasing the ones that they could not withstand.
To give an analogy, If I were to fight a boxer, either I have to die or please him for my survival. And guess what, humans wanted to live and chose the later. This practice put them to please the snakes and treating them as gods.

More on animal worship - http://en.wikipedia.org/wiki/Animal_worship

Thursday, November 06, 2008

Why so many definitions for one? Cloud computing.

There are hundreds of definition for cloud computing, lying around in the internet. I was just wondering why do people give so many defitions for the same thing.

Only after couple of minutes, was I able to figure out that the definitions are targeted for different audience, and not necessarily defined because of the people who were involved in creating the definition could not understand/get it correct.

Then I thought of a common example, rather than a technology.

It's like if I were to define an elephant, one could say it is a animal > mamal > and go on to define it's properties/attributes like it has legs, tusk, eyes, etc. Another definition could be that, an elephant is a domesticated animal in the temple, which is a vital part of the ceremonies in the temple. The later definition is just a subset of the earlier definition. The later may well fit the definition of an temple elephant but not the elephant as a whole.

Now the analogy, the various subsets of the cloud computing could be,
[1] Building data centers and running software to be consumed.
[2] Running all the applications online and using browser as the interface to work.
[3] Flexibility to store any of your data, somewhere in the cloud and pull it out as and when required.
And there are much more of these definitions, let me leave it at that.

The three different definitions of cloud computing above, are all like defining what a temple elephant is. The definitions itself could not be called invalid, say the audience for the definition #2 could be the end users who do not have to worry about the data center or virtualization or what goes behind or beyond their scope.

But for a company that is part of the cloud computing paradigm, all the three definitions are subsets of what cloud computing is in a whole.