Tuesday, June 18, 2013

IsPalindrome generic function (C#)

Excerpt from .NET 4.0 Generic's Guide, there's an example on testing whether a string is Palindrome using a Stack object. I decided to create a a Queue based method. One additional tip was to reverse the Queue object.See code below:
Code:
public static bool IsPalindromic<T>(IEnumerable<T> inputSequence)   
       where T : IComparable  
     {  
       Queue<T> buffer = new Queue<T>();  
       foreach (T element in inputSequence)  
       {  
         buffer.Enqueue(element);  
         temp.Enqueue(element);  
       }  
       buffer = new Queue<T>(buffer.Reverse());  
       for (int i = 0; i < inputSequence.Count(); i++)  
       {  
         if (buffer.Dequeue().CompareTo(inputSequence.ElementAt(i)) == 0)  
         {  
           continue;  
         }  
         else  
           return false;  
       }  
       return true;  
     }  

Greg

0 comments:

Post a Comment