DCSIMG
February 2009 - Posts - IHateSpaghetti {code}

IHateSpaghetti {code}

VSX, DSL and Beyond by Eyal Lantzman

Syndication

Coding / Architecture

Extensibility /DSL

Projects

Articles

February 2009 - Posts

After a month of absence - blog carnival returns!

I had some time this weekend to catch-up so here are the highlights (a lot of Domain Driven Design (DDD) !!!)

DSL

DDD

SOA

Parallel Programming

Power shell

NDepend

Web platforms

Azure

Get Started Developing on Windows Azure?

If you’re a developer and you’re new to Windows Azure, start here! You’ll see what you need to download and install, and how to create a simple “Hello World” Windows Azure application.

Deploy a Windows Azure Application

You’ll see what it takes to move your application into the cloud – you’ll see how to request and register a token, how to upload your Windows Azure application and how to move it between staging and production in the cloud.

Store Blobs in Windows Azure Storage?

Learn how to leverage Windows Azure storage to store data as blobs. You’ll learn about blob storage, containers and the API that makes it easy to manage everything from managed code.

Leverage Queues in Windows Azure?

Learn how to use queues to facilitate communication between Web and Worker roles in Windows Azure.

Debugging Tips for Windows Azure Applications

The Windows Azure SDK includes a development fabric that provides a "cloud on your desktop." In this screencast, learn how to debug your Windows Azure applications in this environment.

Store Data in Windows Azure Tables

Learn how to get started with Windows Azure tables. You'll see how to create tables and then add, edit and delete data.

 

.NetServices

Get Started with .NET Services?

.NET Services are a set of highly scalable building blocks for programming in the cloud. In this brief screencast, you'll learn about the registration process, the SDK and the built-in samples - everything you need to know in order to get started.

Harness the Microsoft .NET Service Bus?

The .NET Service Bus makes it easy to access your Web services no matter where they are. In this brief screencast, you'll see how to take a basic Windows Communication Foundation (WCF) service and expose it to the Internet with the .NET Service Bus.

 

LiveServices

Get Started with the Live Framework?

If you are looking to get started developing with the Live Framework, this is the place to start! In this screencast you'll learn how to get a Live Services token and what you need to download in order to start writing Live Framework applications.

Use the Microsoft Live Framework Resource Browser?

The Live Framework Resource Model is a simple, straightforward information model based on entities, collections and relationships. In this brief screencast you'll learn how to navigate the relationships between entities by using the Live Framework Resource Browser, which is a tool that ships with the Live Framework SDK.

Shachar left me a comment in my post Interview Question #5 - Binary permutations and I at first to answer as a comment but then thought that I will be a great post by it self (you will be the judge of that).

Let me tell you a personal story. I was one of the first people that interviewed for a developer positing at Microsoft Herzeliya, long before any large recruitments.

So I went there, confident that I be able to pass the interview and start my career at Microsoft. The confidence was based on my experience in various IT companies doing various technology focused roles. And I was quite good or at least that what my colleagues and managers told me.

The interview day was consistent of two interviews.

The first interview was on how would I implement virtual memory (!!!). WTF ? Fortunately I took the course in operating systems a year or two ago as part of my CS degree, so I knew the answer to that one, although I felt very uncomfortable and unconfident from this point forward. The second question in the first interview was - how would I implement DNS, same luck here, I took a networking course and had a vague idea about the implementation.

The second interview was algorithmic in nature - I had to implement stack and queue + some questions on this - this was relatively no difficult. The second question in the second interview blown my mind: Find the shortest route between start point and end point in a rectangular space. In that space can be one or more polygonal shapes they are the obstacles.

If anyone has an answer to the question above - it will be appreciated, because I don't know the answer !!!

My point is this - there are two kinds of interviews (can be more but I mean for .NET developers):

1) IT companies

2) Large software companies such as Microsoft, Amazon, Google, etc.

The IT companies deals with software integration - most of the time you think on how to integrate a technology X in your organization the best way (and have fun doing that), or how do implement functionality Y using technology A, B or C.

However, the software companies are usually the ones providing the the technologies and thus they need something else - the need knowledge in operating systems, networks and algorithms! At IT interview you will be asked what are the pro's and con's in store procedures vs. queries, and at Oracle you will be asked - what kind of optimization can you do to a query that will reduce the memory footprint (made that one up).

Final thought on the matter - I think that developers that do know how the OS is working and how do various algorithms perform and what are they limitations and when to use recursion (and when no to use it) are considered better by the IT organization they working for - and there quite a lot of those people - some of them writing blogs at this very blogging host!

This post is a part of the Interview Question Series posts.

Three way partition?! Is there a two way partition or a four way partition ?!

Well X way partition problems are simply dividing the array/collection into X compartments each with it's own distinct feature/property.

One way compartment sort is too simple (just return the array without doing anything) :-)

Two compartments are not difficult as well - you just need to pointers one to the left side one to the right side and you advance the pointers from both sides towards middle when you can't move you swap between them. And the main loop is running while the left side hasn't crossed the right side. If you want the code just drop me a line...

The complexity is greatly increases when the number of compartments is more then two (and you bound to a memory complexity of O(1) - otherwise one could create a list per compartment, go through the source array and map the items to the corresponding list and at the end just merge the lists by the needed order).

So, what are our options - we can sort using some sort efficient sort - O(NlogN). Quite good but can we do better ? The answer is yes (otherwise I wouldn't bother...)

   1: namespace Question6_ThreeWayPartition
   2: {
   3:   /// <summary>
   4:   /// Question: When given unsorted array of integers sort the array so that in the beggining will be all
   5:   /// the negative numbers (unordered), then zeros and then all the positives (unordered)
   6:   /// </summary>
   7:   class Program
   8:   {
   9:     static void Main(string[] args)
  10:     {
  11:       //test the sorting using 10 random arrays
  12:       for (int i = 0; i < 10; i++)
  13:       {
  14:         //generate the random array and a copy (in order to test in the two methods)
  15:         int[] array = Generate(15);
  16:         
  17:         //print the original
  18:         Console.Write("\nOrigianl array: ");
  19:         PrintArray(array);
  20:  
  21:         SortUsingThreeWayPartition(array);
  22:         Console.Write("\nModified array: ");
  23:         PrintArray(array);
  24:       }
  25:  
  26:       Console.ReadLine();
  27:     }
  28:  
  29:     /// <summary>
  30:     /// Random array generator (range is [-3,3])
  31:     /// </summary>
  32:     /// <param name="length">size of array</param>
  33:     /// <returns>the array</returns>
  34:     private static int[] Generate(int length)
  35:     {
  36:       int[] array = new int[length];
  37:       Random randomGenerator = new Random();
  38:       for (int i = 0; i < array.Length; i++)
  39:       {
  40:         array[i] = randomGenerator.Next(-3, 4); //between -3 and 3 in order to give enough chance for the zeros
  41:       }
  42:       return array;
  43:     }
  44:  
  45:     /// <summary>
  46:     /// Sorting method
  47:     /// </summary>
  48:     /// <param name="array"></param>
  49:     public static void SortUsingThreeWayPartition(int[] array)
  50:     {
  51:       int firstPartition = 0, secondPartition = 0, thirdPartition = array.Length - 1;
  52:  
  53:       while (secondPartition <= thirdPartition)
  54:       {
  55:         if (array[secondPartition] > 0)
  56:         {
  57:           Swap(array, secondPartition, thirdPartition--); //move to the third partition
  58:         }
  59:         else if (array[secondPartition] < 0)
  60:         {
  61:           Swap(array, firstPartition++, secondPartition++); //move to the first partition
  62:         }
  63:         else
  64:         {
  65:           secondPartition++; // leave in the second partition
  66:         }
  67:       }
  68:     }
  69:  
  70:     /// <summary>
  71:     /// Swaps between two values in array
  72:     /// </summary>
  73:     /// <param name="array"></param>
  74:     /// <param name="i"></param>
  75:     /// <param name="j"></param>
  76:     private static void Swap(int[] array, int i, int j)
  77:     {
  78:       if (i == j)
  79:         return;
  80:  
  81:       int temp = array[i];
  82:       array[i] = array[j];
  83:       array[j] = temp;
  84:     }
  85:     
  86:     /// <summary>
  87:     /// Simple method that prints the array
  88:     /// </summary>
  89:     /// <param name="array"></param>
  90:     private static void PrintArray(int[] array)
  91:     {
  92:       foreach (int i in array)
  93:       {
  94:         Console.Write(i);
  95:         Console.Write(" ");
  96:       }
  97:       Console.WriteLine();
  98:     }
  99:   }
 100: }

You can generalize the algorithm using generics by providing a mapping function that maps the item to specific compartment (1, 2 or 3)  as following:

   1: /// <summary>
   2: /// Sorting method
   3: /// </summary>
   4: /// <param name="array"></param>
   5: /// <param name="mapper">mapping function where to move the item:
   6: /// 1 - 1st partition 
   7: /// 2 - 2nd partition
   8: /// 3 - 3rd partition
   9: /// </param>
  10: /// <typeparam name="T">array item type</typeparam>
  11: public static void SortUsingThreeWayPartition<T>(T[] array, Func<T, int> mapper)
  12: {
  13:   int firstPartition = 0, secondPartition = 0, thirdPartition = array.Length - 1;
  14:  
  15:   while (secondPartition <= thirdPartition)
  16:   {
  17:     int partition = mapper(array[secondPartition]);
  18:     switch (partition)
  19:     {
  20:       case 1:
  21:         Swap(array, firstPartition++, secondPartition++); //move to the first partition
  22:         break;
  23:       case 2:
  24:         secondPartition++; // leave in the second partition
  25:         break;
  26:       case 3:
  27:         Swap(array, secondPartition, thirdPartition--); //move to the third partition
  28:         break;
  29:     }
  30:   }
  31: }
  32:  
  33: /// <summary>
  34: /// Swaps between two generic items in array
  35: /// </summary>
  36: /// <typeparam name="T">array item type</typeparam>
  37: /// <param name="array"></param>
  38: /// <param name="i"></param>
  39: /// <param name="j"></param>
  40: private static void Swap<T>(T[] array, int i, int j)
  41: {
  42:   if (i == j)
  43:     return;
  44:   T temp = array[i];
  45:   array[i] = array[j];
  46:   array[j] = temp;
  47: }

And in order to solve the problem above all you need is to create the correct mapping as following:

   1: //For the problem above you can using the following code:
   2: SortUsingThreeWayPartition<int>(arrayCopy,
   3:   //mapper anonymous function
   4:   (num) => 
   5:   {
   6:     //if num is negative - map to the 1st partition
   7:     if (num < 0)
   8:       return 1;
   9:     //if num is zero - map to the 2nd partition
  10:     else if (num == 0)
  11:       return 2;
  12:     //if num is positive - map to the 3rd partition
  13:     else return 3;
  14:   });
Posted by Eyal | with no comments

This post is a part of the Interview Question Series posts.

 

Question for a given positive integer n print all the permutation of a binary number of size n.

Example:

n=3 => 000, 001, 010, 011, 100, 101, 110, 111

In general there are 2^n permutations for a given n.

 

Try to solve it by yourself first...

 

The code below shows two approaches to these kind of questions a mathematical one - just loop 2^n times and switch the left most bit if the resulting bit is zero then shift then switch the next one and so on. The second approach is using recursive algorithm to permute all the variations.

   1: namespace Recursion5
   2: {
   3:   /// <summary>
   4:   /// Question:
   5:   /// For a given positive int n prints all binary numbers of length n
   6:   /// </summary>
   7:   class Program
   8:   {
   9:     static void Main(string[] args)
  10:     {
  11:       for (int i = 1; i < 5; i++)
  12:       {
  13:         Console.WriteLine("Recursive binaries for {0}", i);
  14:         RecursivePrintBinaries(i);
  15:  
  16:         Console.WriteLine("Iterative binaries for {0}", i);
  17:         InterativePrintBinaries(i);
  18:       }
  19:       Console.ReadLine();
  20:     }
  21:  
  22:     /// <summary>
  23:     /// Interative print binaries method
  24:     /// </summary>
  25:     /// <param name="n"></param>
  26:     public static void InterativePrintBinaries(int n)
  27:     {
  28:       System.Collections.BitArray array = new System.Collections.BitArray(n,false);
  29:  
  30:       //calculate the total runs - each bit can be 1 or 0 and there are n of those
  31:       int totalRuns = (int)Math.Pow(2,n);
  32:       do
  33:       {
  34:         //First of all print the current array
  35:         PrintBinary(array);
  36:  
  37:         //flip the first bit (and potentialy cause a chain reaction that will flip other bits as well
  38:         FlipBit(array);
  39:  
  40:         totalRuns--;
  41:       }
  42:       while (totalRuns > 0);
  43:     }
  44:  
  45:     private static void FlipBit(System.Collections.BitArray array)
  46:     {
  47:       //flip the last bit
  48:       array[array.Length - 1] = !array[array.Length - 1];
  49:  
  50:       for (int j = array.Length- 1; j > 0; j--)
  51:       {
  52:         //if previous bit is fliped to zero - the current bit should flip to one
  53:         if (!array[j])
  54:         {
  55:           array[j - 1] = !array[j - 1];
  56:         }
  57:         else
  58:         {
  59:           //stop the bit flipping loop
  60:           break;
  61:         }
  62:       }
  63:     }
  64:  
  65:     /// <summary>
  66:     /// Utility method that prints the bits array
  67:     /// </summary>
  68:     /// <param name="array"></param>
  69:     private static void PrintBinary(System.Collections.BitArray array)
  70:     {
  71:       for (int i = 0; i < array.Length; i++)
  72:       {
  73:         Console.Write(array[i] ? 1 : 0);
  74:       }
  75:       Console.WriteLine();
  76:     }
  77:  
  78:     /// <summary>
  79:     /// Print Binaries method
  80:     /// </summary>
  81:     /// <param name="i"></param>
  82:     public static void RecursivePrintBinaries(int i)
  83:     {
  84:       RecursivePrintBinaries(new bool[i], 0);
  85:     }
  86:  
  87:     /// <summary>
  88:     /// Recursive method that processes array of bits at index idx
  89:     /// </summary>
  90:     /// <param name="array"></param>
  91:     /// <param name="idx"></param>
  92:     private static void RecursivePrintBinaries(bool[] array, int idx)
  93:     {
  94:       //end of processing - print the outcome
  95:       if (idx >= array.Length)
  96:       {
  97:         PrintBinary(array);
  98:         return;
  99:       }
 100:  
 101:       //The first options is to use 0 at index idx in the bit array
 102:       array[idx] = false;
 103:       RecursivePrintBinaries(array, idx + 1);
 104:  
 105:       //The first options is to use 1 at index idx in the bit array
 106:       array[idx] = true;
 107:       RecursivePrintBinaries(array, idx + 1);
 108:     }
 109:  
 110:     /// <summary>
 111:     /// Utility method that prints the bool array
 112:     /// </summary>
 113:     /// <param name="array"></param>
 114:     private static void PrintBinary(bool[] array)
 115:     {
 116:       for (int i = 0; i < array.Length; i++)
 117:       {
 118:         Console.Write(array[i]?1:0);
 119:       }
 120:       Console.WriteLine();
 121:     }
 122:   }
 123: }
In most questions that you need to create permutations you can use the mathematical approach but most of the time the code will be more complicated than the recursive approach.

Clemens has an interesting post on how to use MEF and the new VS Team Architect Layer Diagram and detect various Anti-Patterns.

Microsoft has released a February update of the Azure Services Training Kit. The training kit is based on a hands-on lab at PDC '08 and includes resources providing background information and training examples of developing software on the Azure Services Platform.

Overview

The Azure Services Training Kit includes a comprehensive set of technical content including hands-on labs, presentations, and demos that are designed to help you learn how to use the Azure Services Platform. The February release includes the following updates:
  • 19 demo scripts that walkthrough several of the services
  • 10 presentations covering the entire Azure Services Platform
  • 3 additional hands-on labs for Live Services


This technical content covers services including: Windows Azure, .NET Services, SQL Services, and Live Services.


Updated: Added speaker notes to the PowerPoint presentations.
Posted by Eyal | with no comments
תגים:, , ,

This post is a part of the Interview Question Series posts.

 

Question: Write a method that prints all the permutations of a given word (string).

Use the following signature: void PrintPermutations(string word) and solve in recursion.

 

Try to solve this by yourself first!

Notice that for a string with length n the number of permutations are n! (factor of n).

 

 

Anyway here's the solution:

The key to solving this problem is to understand that for each char in string there are two options

1) Select it to the current variation (line 80)

2) Not to select it (line 79)

 

   1: namespace Recursion3
   2: {
   3:   /// <summary>
   4:   /// Question:
   5:   /// For a given string prints all it's permutations
   6:   /// Use the following signature: void PrintPermutations(string word) and solve in recursion.
   7:   /// </summary>
   8:   class Program
   9:   {
  10:     static void Main(string[] args)
  11:     {
  12:       string input = string.Empty;
  13:       while (input != null)
  14:       {
  15:         Console.Write("Permutation target: ");
  16:         input = Console.ReadLine();
  17:         long expected = Factor(input.Length);
  18:         if (expected < 0)
  19:         {
  20:           //overflow
  21:           Console.WriteLine("The string is too long! Try again");
  22:           continue;
  23:         }
  24:  
  25:         Console.WriteLine("\nExpecting {0} results, To abort press a or A (any other to continue)", expected);
  26:         if (StringComparer.OrdinalIgnoreCase.Compare("a",Console.ReadLine())==0)
  27:           continue;
  28:  
  29:         //permutate
  30:         PrintPermutations(input);
  31:       }
  32:     }
  33:  
  34:     /// <summary>
  35:     /// Returns a factor of n (n!)
  36:     /// </summary>
  37:     /// <param name="n"></param>
  38:     /// <returns></returns>
  39:     private static long Factor(long n)
  40:     {
  41:       if (n <=1)
  42:         return 1;
  43:       return n * Factor(n - 1);
  44:     }
  45:  
  46:     /// <summary>
  47:     /// Solution using a bootstrap function
  48:     /// </summary>
  49:     /// <param name="word"></param>
  50:     public static void PrintPermutations(string word)
  51:     {
  52:       if (string.IsNullOrEmpty(word))
  53:         return;
  54:  
  55:       PrintPermutations(string.Empty, word,0);
  56:     }
  57:  
  58:     /// <summary>
  59:     /// Bootstraped function
  60:     /// </summary>
  61:     /// <param name="variation"></param>
  62:     /// <param name="word"></param>
  63:     /// <param name="charIndex"></param>
  64:     private static void PrintPermutations(string variation, string word, int charIndex)
  65:     {
  66:       ////when the word is empty then the variation is complete
  67:       if (string.IsNullOrEmpty(word))
  68:       {
  69:         Console.WriteLine(variation);
  70:         return;
  71:       }
  72:  
  73:       //detect permutation end
  74:       if (charIndex >= word.Length)
  75:       {
  76:         return;
  77:       }
  78:  
  79:       PrintPermutations(variation, word,charIndex +1); //the first option is not to use the char at charIndex
  80:       PrintPermutations(variation + word[charIndex].ToString(), RemoveChar(word,charIndex), 0); //the second options is to use the char at charIndex
  81:     }
  82:  
  83:     /// <summary>
  84:     /// Utility method that removes char at charIndex from word and returns the new word
  85:     /// </summary>
  86:     /// <param name="word"></param>
  87:     /// <param name="charIndex"></param>
  88:     /// <returns></returns>
  89:     private static string RemoveChar(string word, int charIndex)
  90:     {
  91:       if (word.Length - 1 == charIndex)
  92:         return word.Substring(0, charIndex);
  93:  
  94:       return word.Substring(0, charIndex) + word.Substring(charIndex + 1);
  95:     }
  96:   }
  97: }
Posted by Eyal | 4 comment(s)

This post is a part of the Interview Question Series posts.

Question: What is the fastest way to find minimum and maximum in (unsorted) array? How many comparisons will be in array of length N?

The runtime complexity is obvious - in order to find the minimum or maximum we have to go through all the items in an array - O(n), the question is how can we minimize the number of comparisons.

Well let's see , the naive approaches are find loop through array and find minimum then loop again and find maximum - the number of comparisons are 2n. However we can do better:

   1: int mininmum;
   2: int maximum;
   3:  
   4: //assuming the array has more than 2 items
   5: if (arr[0] > arr[1])
   6: {
   7:     maximum = arr[0];
   8:     minimum = arr[1];
   9: }
  10: else
  11: {
  12:     maximum = arr[1];
  13:     minimum = arr[0];
  14: }
  15:  
  16: for (int i=2; i < length; i++)
  17: {
  18:     if (arr[i] > maximum)
  19:         maximum = arr[i];
  20:     else if (arr[i] < minimum)
  21:         minimum = arr[i];
  22: }
  23: //The maximum and minimum found
 
Is it really better ? Yes ! How much better - not that much - 2n -2 comparisons in the worst case. Hmmm is it the best we can do? No - we can apply the logic for first two items on all the other items as well... How?
 
   1: int minimum, maximum;
   2: int i;
   3:  
   4: if (arr.length % 2 == 0)
   5: {
   6:     if (arr[0]>arr[1])
   7:     {
   8:         minimum = arr[0];
   9:         maximum = arr[1];
  10:     }
  11:     else
  12:     {
  13:         maximum = arr[1];
  14:         minimum = arr[0];
  15:     }
  16:     i = 2; //start processing from index 2
  17: }
  18: else
  19: {
  20:     maximum = minimum = arr[0];
  21:     i = 1; //start processing from index 1
  22: }
  23:  
  24: for (/*i was already declared*/; i < arr.length-1; i=i+2)
  25: {
  26:     if (arr[i] > arr[i+1])
  27:     {
  28:         //compare the large number with the maximum
  29:         if (maximum < arr[i])
  30:             maximum = arr[i];
  31:  
  32:         //and the smaller number with the minimum
  33:         if (minimum > arr[i+1])
  34:             minimum = arr[i+1];
  35:     }
  36:     else
  37:     {
  38:         //compare the large number with the maximum
  39:         if (maximum < arr[i+1])
  40:             maximum = arr[i+1];
  41:  
  42:         //and the smaller number with the minimum
  43:         if (minimum > arr[i])
  44:             minimum = arr[i];
  45:     }
  46: }
  47:  
  48: //The maximum and minimum will be found when the code will reach here
 
That was a lot of code and seems that it's still doing 2n-2 comparisons. Well not really - the thing is the comparison in line 26 will be running only n/2 times and from that point there are two routes the first through lines 29, 33 and the second through lines 39, 43 - meaning additional n/2 + n/2 (one of the maximum and one for the minimum) comparisons.

If you sum all n's you'll get 3n/2 comparisons, obviously better than 2n ;-)

Posted by Eyal | with no comments

What is T4? You can find you more info here.

Clarius opened a blog for their Visual T4 generator.

You can find more about the features and price, you can download a free community edition as well for VS2005 and VS2008.

 

 

Posted by Eyal | 1 comment(s)
תגים:, , , ,

This post is a part of the Interview Question Series posts.

Check if the string s2 is a sub string of string s1 (when s2 is null or empty then return true)
You can use only string's indexer, string's Equals function, string's length function and string's substring function.
Use the following signature: bool IsSubstring(string s1, string s2) and solve in recursion.

Try to solve this by yourself first....

 

But anyway here's the solution for the problem:

There are two versions one of them is not that efficient (creates bunch of string instances) but more elegant.

Tip: solve using the elegant way and then suggest solving this in more efficient way or ask the interview what he prefers ;-)

 
   1: namespace Recursion2
   2: {
   3:   /// <summary>
   4:   /// Question:
   5:   /// Check if the string s2 is a substring of strign s1 (when s2 is null or empty then return true)
   6:   /// You can use only string indexer, string Equals, string length and string Substring.
   7:   /// Use the following signature: bool IsSubstring(string s1, string s2) and solve in recursion.
   8:   /// </summary>
   9:   class Program
  10:   {
  11:     /// <summary>
  12:     /// Test the solution
  13:     /// </summary>
  14:     /// <param name="args"></param>
  15:     static void Main(string[] args)
  16:     {
  17:       string[] s1s = new string[] { "aaabbbccc", "abc", "cba", "ddca", null, string.Empty };
  18:       string[] s2s = new string[] { "aa", "bb", "cc", "dd", "a", "b", "c", "d", "z", string.Empty, null };
  19:  
  20:       s1s.ToList().ForEach(
  21:         (s1) =>
  22:         {
  23:           s2s.ToList().ForEach(
  24:             (s2) =>
  25:             {
  26:               Console.WriteLine("Ver1: {0} is substring of {1} = {2}", s2 ?? "NULL", s1 ?? "NULL",IsSubstringVer1(s1,s2));
  27:               Console.WriteLine("Ver2: {0} is substring of {1} = {2}", s2 ?? "NULL", s1 ?? "NULL", IsSubstringVer2(s1, s2));
  28:             }
  29:           );
  30:         }
  31:       );
  32:  
  33:       Console.ReadLine();
  34:     }
  35:  
  36:     /// <summary>
  37:     /// Solution - Ver1
  38:     /// Con: Put high pressure on the GAC (create a lot of strings during the process)
  39:     /// Pro: No need to add additional funtions
  40:     /// </summary>
  41:     /// <param name="s1">string</param>
  42:     /// <param name="s2">sub string</param>
  43:     /// <returns>if s2 is s1's substing</returns>
  44:     public static bool IsSubstringVer1(string s1, string s2)
  45:     {
  46:       if (string.IsNullOrEmpty(s2))
  47:         return true;
  48:  
  49:       if (string.IsNullOrEmpty(s1))
  50:         return string.IsNullOrEmpty(s2);
  51:  
  52:       if (s2.Length == s1.Length)
  53:         return s2.Equals(s1);
  54:  
  55:       if (s2.Length > s1.Length)
  56:         return false;
  57:  
  58:       return IsSubstringVer1(s1.Substring(1), s2) //the first combination is to remove the first char from s1
  59:         || IsSubstringVer1(s1.Substring(0, s1.Length - 1), s2); //the second combination is to remove the last char from s2
  60:     }
  61:  
  62:     /// <summary>
  63:     /// Solution Ver2
  64:     /// Pro: No string allocations
  65:     /// Con: Extra "bootstraped" function
  66:     /// </summary>
  67:     /// <param name="s1"></param>
  68:     /// <param name="s2"></param>
  69:     /// <returns></returns>
  70:     public static bool IsSubstringVer2(string s1, string s2)
  71:     {
  72:       if (string.IsNullOrEmpty(s2))
  73:         return true;
  74:  
  75:       if (string.IsNullOrEmpty(s1))
  76:         return string.IsNullOrEmpty(s2);
  77:  
  78:       //bootstrap
  79:       return IsSubstringVer2(s1,1,0,s2,0);
  80:     }
  81:  
  82:     /// <summary>
  83:     /// Bootstrapped function
  84:     /// </summary>
  85:     /// <param name="s1"></param>
  86:     /// <param name="fallBackIndex">in case of missmach fallback to index</param>
  87:     /// <param name="s1Index">process s1 in index...</param>
  88:     /// <param name="s2"></param>
  89:     /// <param name="s2Index">process s2 in index...</param>
  90:     /// <returns></returns>
  91:     private static bool IsSubstringVer2(string s1, int fallBackIndex, int s1Index, string s2, int s2Index)
  92:     {
  93:       if (s2Index >= s2.Length)
  94:         return true; //if we reached here it means that s2 is substring of s1
  95:  
  96:       if (s1Index >= s1.Length)
  97:         return false; //if we reached here it means that s2 is not substring of s1
  98:  
  99:  
 100:       if (s1[s1Index] == s2[s2Index])
 101:         //if the current chars are the same proceed to the next
 102:         return IsSubstringVer2(s1, fallBackIndex, s1Index + 1, s2, s2Index + 1);
 103:  
 104:       //fall back and start over
 105:       return IsSubstringVer2(s1, fallBackIndex + 1, fallBackIndex, s2, 0);
 106:     }
 107:   }
 108: }

If you have found a bug or have a nicer way to solve this - share it.

This post is a part of the Interview Question Series posts.

For a list of integers (positive and negative) check if there's a combination within them that when you will sum them the result will be a specific amount.
Use the following signature: bool IsCover(int[] values, int amount) and solve in recursion.

Example: for the following list { 5, 22, 13, 5, 7, -4 } and amount 23 the answer will be true (5 + (-4) + 22 = 23)

 

Try to solve this by yourself first....

 

But anyway here's the solution for the problem:

   1: namespace Recursion1
   2: {
   3:   /// <summary>
   4:   /// Question:
   5:   /// For a list of integers (positive and negative) check if there's 
   6:   /// a combination within them that when you will sum them the result will be a specific amout.
   7:   /// Use the following signature: bool IsCover(int[] values, int amount) and solve in recursion.
   8:   /// </summary>
   9:   class Program
  10:   {
  11:     /// <summary>
  12:     /// Test the solution
  13:     /// </summary>
  14:     /// <param name="args"></param>
  15:     static void Main(string[] args)
  16:     {
  17:       int[] values = new int[] { 5, 22, 13, 5, 7, -4 };
  18:       Console.WriteLine("List: ");
  19:       values.ToList().ForEach(
  20:         (val)=>
  21:           {
  22:             Console.Write(val);
  23:             Console.Write(" ");
  24:           });
  25:       Console.WriteLine();
  26:  
  27:       new int[]{42,31,-5,17,13,23}.ToList().ForEach(
  28:         (amount)=>
  29:           {
  30:             Console.WriteLine("Can cover amount {0} = {1}", amount, IsCover(values, amount));
  31:           });
  32:  
  33:       Console.ReadLine();
  34:     }
  35:  
  36:     /// <summary>
  37:     /// Solution
  38:     /// </summary>
  39:     /// <param name="values">list of numbers</param>
  40:     /// <param name="amount">amount to cover by the values</param>
  41:     /// <returns>if can be covered or not</returns>
  42:     public static bool IsCover(int[] values, int amount)
  43:     {
  44:       if (values==null || values.Length==0)
  45:         return amount == 0;
  46:  
  47:       //bootstrap
  48:       return IsCover(values, 0, amount);
  49:     }
  50:  
  51:     /// <summary>
  52:     /// Bootstraped method
  53:     /// </summary>
  54:     /// <param name="values"></param>
  55:     /// <param name="i">starting index</param>
  56:     /// <param name="amount"></param>
  57:     /// <returns></returns>
  58:     private static bool IsCover(int[] values, int i, int amount)
  59:     {
  60:       if (i >= values.Length)
  61:         return amount == 0;
  62:  
  63:       return
  64:         IsCover(values, i + 1, amount - values[i]) //try to cover using value from index i
  65:         || IsCover(values, i + 1, amount); //try to cover without using the value in index i
  66:     }
  67:   }
  68: }
 
If you have found a bug or have a nicer way to solve this - share it.

I've decided to blog about various interesting interview questions - for educational purposes and because I get to help my friends prepare to interviews and this can save me some time ;-)

In general the whiteboard questions are divide to the following sections:

  • General recursion
  • String manipulation
  • Bit manipulation (usually for chip manufactures or other low level technology oriented companies)
  • Data structures
  • Performance optimization (usually as a follow-up to a different question)
  • Others (nothing pops into my mind but I'm sure there are more)

If you have challenging question that you want me to answer drop me a line...

Posted by Eyal | 2 comment(s)