Implement a method to perform basic string compression using the counts of repeated characters.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace _1_05_CompressionString

   7: {

   8:     class Program

   9:     {

  10:         private static int countCompression(string str)

  11:         {

  12:             int size = 0;

  13:  

  14:             char last = str[0];

  15:             int count = 1;

  16:  

  17:             for (int i = 0; i < str.Length; i++)

  18:             {

  19:                 if (str[i] == last)

  20:                 {

  21:                     count++;

  22:                 }

  23:                 else

  24:                 {

  25:                     last = str[i];

  26:                     size += 1 + count.ToString().Length;

  27:                     count = 1;

  28:                 }

  29:             }

  30:             size += 1 + count.ToString().Length;

  31:             return size;

  32:         }

  33:  

  34:  

  35:         private static string Compression1(string str)

  36:         {

  37:             int size = countCompression(str);

  38:             if (size >= str.Length)

  39:             {

  40:                 return str;

  41:             }

  42:  

  43:             StringBuilder stb = new StringBuilder();

  44:             char last = str[0];

  45:             int count = 1;

  46:  

  47:             for (int i = 1; i < str.Length; i++)

  48:             {

  49:                 if (last == str[i])

  50:                 {

  51:                     count++;

  52:                 }

  53:                 else

  54:                 {

  55:                     stb.Append(last);

  56:                     stb.Append(count);

  57:                     last = str[i];

  58:                     count = 1;

  59:                 }

  60:             }

  61:             stb.Append(last);

  62:             stb.Append(count);

  63:  

  64:             return stb.ToString();

  65:         }

  66:  

  67:         private static string Compression2(string str)

  68:         {

  69:             int size = countCompression(str);

  70:             if (size >= str.Length)

  71:             {

  72:                 return str;

  73:             }

  74:  

  75:             string result = string.Empty;

  76:             char last = str[0];

  77:             int count = 1;

  78:  

  79:             for (int i = 1; i < str.Length; i++)

  80:             {

  81:                 if (last == str[i])

  82:                 {

  83:                     count++;

  84:                 }

  85:                 else

  86:                 {

  87:                     result += last.ToString();

  88:                     result += count.ToString();

  89:                     last = str[i];

  90:                     count = 1;

  91:                 }

  92:             }

  93:             result += last.ToString();

  94:             result += count.ToString();

  95:  

  96:             return result;

  97:         }

  98:  

  99:         static void Main(string[] args)

 100:         {

 101:             string str = "abbcccccccccccccccccccccccccccde";

 102:  

 103:             Console.WriteLine("{0} : {1}", str, countCompression(str)); 

 104:  

 105:             Console.WriteLine("{0} : {1}", str, Compression1(str)); 

 106:             Console.WriteLine("{0} : {1}", str, Compression2(str));

 107:  

 108:             Console.ReadKey();

 109:         }

 110:     }

 111: }

Advertisements

Implement an algorithm to determine if a string has all unique characters.

 

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IsUniqueCharacters

   7: {

   8:     class Program

   9:     {

  10:         private static bool isUniqueChars(string str)

  11:         {          

  12:  

  13:             bool[] arrBool = new bool[256];

  14:  

  15:             for (int i = 0; i < str.Length; i++)

  16:             {

  17:                 int val = str[i];

  18:                 if (arrBool[val])

  19:                     return false;

  20:  

  21:                 arrBool[val] = true;

  22:             }

  23:  

  24:             return true;

  25:         }

  26:  

  27:         private static void FindUniqueChars(string str)

  28:         {

  29:             if (!isUniqueChars(str))

  30:             {

  31:                 Console.WriteLine("No unique string");

  32:             }

  33:  

  34:             int[] arrIndex = new int[256];

  35:             for (int i = 0; i < str.Length; i++)

  36:             {

  37:                 arrIndex[str[i]]++;

  38:             }

  39:  

  40:             Console.Write("Duplicate chars in ({0}) = ", str);

  41:             for (int j = 0; j < 256; j++)

  42:             {

  43:                 if (arrIndex[j] > 1)

  44:                     Console.Write("{0} ", (char)j);

  45:             }

  46:             Console.WriteLine();

  47:         }

  48:  

  49:  

  50:         static void Main(string[] args)

  51:         {

  52:             string[] arrStrings = new string[] { "abcdedisp", "akcidiugs", "sacddes", "abcsnil", "abckiipdnsu", "iiiiiiii", "aaaiiimmm" };

  53:  

  54:             foreach (string str in arrStrings)

  55:             {

  56:                 if (isUniqueChars(str))

  57:                     Console.WriteLine("{0} is Uniq", str);

  58:                 else

  59:                     Console.WriteLine("{0} is NOT Uniq", str);

  60:  

  61:                 FindUniqueChars(str);

  62:  

  63:             }

  64:  

  65:             Console.ReadKey();

  66:         }

  67:     }

  68: }

Please make a list of all the different types of testing a tester can do.

I like this question b/c then candidates have all these categories at the top of their heads for use in testing questions later in the day.

There are different names for the same kinds of testing, so candidates may use different terms. If you’re not sure, ask them to clarify.

A good answer will include many of the following: (the farther down on the list, the more likely a candidate will miss it)

· Black box – testing without knowing how the code works

· White box – testing when you know exactly what the code is doing

· Gray box – a combination of black and white box

· Automation – using code to create test cases that can be run over and over at the click of a mouse

· Functionality – the basic functional aspects. Ex can you print, save?

· UI (User Interface) –Do buttons and links take you to the right place? Can you find your way around?

· Error handling – if you make a mistake or do something evil, does the product recover gracefully?

· Performance – how fast does the product run under certain conditions?

· Stress – how does the software do when you put stress on it? Heavy loads, fewer resources like memory…

· Stability – how does the software do over time? When it’s been running for days on end?

· Load – how does the software do when lots of people are using it at once?

· Database – is the data getting to and from the database correctly?

· End to End/Integration – testing the code as a full system, rather than testing individual parts

· Component testing – testing the individual parts

· Usability – is the software intuitive to use? Watch actual customers use the product

· Boundary – if a field can take up to 10 characters, test 8, 9 and 10 chars.

· Scalability – can we grow this software to run on more servers and have more customers in the future?

· BVT (Build Verification Test) – basic cases run each time a new build is released)

· API (Application Program Interface) – testing the input/output for an OS service

· Bug Bash – let the whole team (PM, dev, marketing etc) test the product

· Alpha/Beta – let the customers test the product, get their feedback

· Regression – is a bug really fixed? Was anything else broken as a side effect of the fix?

· Compatibility – can the software run on different browsers and operating systems? Backward compatibility for Office and Windows? Upgrades?

· Security – is the software vulnerable to attacks?

· Globalization – is the software world-ready? (ex no hard coded strings)

· Localization – did we break anything when we regionalized the product?

Common Regular expression Patterns

You need a quick list from which to choose regular expression patterns that match
standard items. These standard items could be a social security number, a zip code, a
word containing only characters, an alphanumeric word, an email address, a URL,
dates, or one of many other possible items used throughout business applications.
These patterns can be useful in making sure that a user has input the correct data
and that it is well formed. These patterns can also be used as an extra security measure
to keep hackers from attempting to break your code by entering strange or malformed
input (e.g., SQL injection or cross-site-scripting attacks). Note that these
regular expressions are not a silver bullet that will stop all attacks on your system;
rather, they are an added layer of defense.

• Match only alphanumeric charactersalong with the characters–, +, ., and any
whitespace, with the stipulation that there is at least one of these characters and
no more than 10 of these characters:
^([\w\.+–]|\s){1,10}$
• Match a person’s name, up to 55 characters:
^[a-zA-Z\’\-\s]{1,55}$
• Match a positive or negative integer:
^(\+|\–)?\d+$
• Match a positive or negative floating point number only; this pattern does not
match integers:
^(\+|\–)?(\d*\.\d+)$
Match a floating point or integer number that can have a positive or negative
value:
^(\+|\–)?(\d*\.)?\d+$
• Match a date in the form ##/##/####, where the day and month can be a
one- or two-digit value and the year can only be a four-digit value:
^\d{1,2}\/\d{1,2}\/\d{4}$
• Match a time to be entered in the form ##:## with an optional am or pm extension
(note that this regular expression also handles military time):
^\d{1,2}:\d{2}\s?([ap]m)?$
• Verify if the input is a social security number of the form ###-##-####:
^\d{3}-\d{2}-\d{4}$
• Match an IPv4 address:
^([0-2]?[0-9]?[0-9]\.){3}[0-2]?[0-9]?[0-9]$
• Verify that an email address is in the form name@address where address isnot an
IP address:
^[A-Za-z0-9_\-\.]+@(([A-Za-z0-9\-])+\.)+([A-Za-z\-])+$
Using Common Patterns | 391
• Verify that an email address is in the form name@address where address isan IP
address:
^[A-Za-z0-9_\-\.]+@([0-2]?[0-9]?[0-9]\.){3}[0-2]?[0-9]?[0-9]$
• Match or verify a URL that uses either the HTTP, HTTPS, or FTP protocol.
Note that this regular expression will not match relative URLs:
^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-
9\-\._\?\,\’/\\\+&%\$#\=~])*$
• Match only a dollar amount with the optional $ and + or -preceding characters
(note that any number of decimal places may be added):
^\$?[+-]?[\d,]*(\.\d*)?$
This is similar to the previous regular expression, except that no more than two
decimal places are allowed:
^\$?[+-]?[\d,]*\.?\d{0,2}$
• Match a credit card number to be entered as four sets of four digits separated
with a space, -, or no character at all:
^((\d{4}[- ]?){3}\d{4})$
• Match a zip code to be entered asfive digitswith an optional four-digit extension:
^\d{5}(-\d{4})?$
• Match a North American phone number with an optional area code and an
optional – character to be used in the phone number and no extension:
^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$
• Match a phone number similar to the previous regular expression but allow an
optional five-digit extension prefixed with either ext or extension:
^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}(\s*ext(ension)?[0-9]{5})?$
• Match a full path beginning with the drive letter and optionally match a filename
with a three-character extension (note that no .. characters signifying to
move up the directory hierarchy are allowed, nor isa directory name with a . followed
by an extension):
^[a-zA-Z]:[\\/]([_a-zA-Z0-9]+[\\/]?)*([_a-zA-Z0-9]+\.[_a-zA-Z0-9]{0,3})?$
• Verify if the input password string matches some specific rules for entering a
password (i.e., the password is between 6 and 25 characters in length and contains
alphanumeric characters):
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,25}$
• Determine if any maliciouscharacterswere input by the user. Note that thisregular
expression will not prevent all malicious input, and it also prevents some
valid input, such as last names that contain a single quote:
^([^\)\(\<\>\”\’\%\&\+\;][(-{2})])*$
• Extract a tag from an XHTML, HTML, or XML string. This regular expression
will return the beginning tag and ending tag, including any attributesof the tag.

Note that you will need to replace TAGNAME with the real tag name you want
to search for:
<TAGNAME.*?>(.*?)</TAGNAME>
• Extract a comment line from code. The following regular expression extracts
HTML commentsfrom a web page. Thiscan be useful in determining if any
HTML comments that are leaking sensitive information need to be removed
from your code base before it goes into production:
<!–.*?–>
• Match a C# single line comment:
//.*$
• Match a C# multiline comment:
/\*.*?\*/

Technical Questions

1) Which is better – singly linked list or doubly linked list? What are the pros and cons of using each?
Singly linked list has smaller memory requirement because singly linked list can only be traversed in one direction. Doubly linked lists require more space for each element in the list and elementary operations such as insertion and deletion is more complex since they have to deal with two references. But doubly link lists allow easier manipulation since it allows traversing the list in forward and backward directions.

Singly Linked List vs. Doubly Linked List

· Elements in singly linked list are linked to only the next element in the series while elements are linked with previous and next both elements in doubly linked list.

· Singly linked lists need lesser space while doubly linked list need more space for every block in the list.

· Basic functions like addition or deletion are complicated in doubly linked list because there are two links to deal with but you can easily manipulate the data because you can cross over the list and move back and forth in the list.

2) What’s the difference between Managed code and Native code? Give examples of each you have worked on.

Managed Code:

Managed code runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. Managed code takes advantages of memory management, security and threading services CLR provides.

The managed code is the one generated by C# and other .NET language compilers (IL) and gets finally converted to native code by JIT. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it’s optional.

Native Code:

Native code does not run under CLR and compiles straight to machine code. No free memory management or anything else the CLR provides. Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

I wrote some web applications in C and C++ on the apache on Linux. These are native code applications whose memory is not “managed”, as in, memory isn’t freed (C++’ delete and C’s free, for instance), no reference counting, no garbage collection. I had to take care of these to free allocated memory.

3) What is thread safe code? Give an example of times you’ve used thread safe code.

Thread Safe code is one which runs in a manner that when multiple threads are running simultaneously and are in need of using shared memory, they do not step onto each other or in other words access the shared memory exclusively.

By using thread-safe routines, the risk that one thread will interfere and modify data elements of another thread is eliminated by circumventing potential data race situations with coordinated access to shared data.

Implement a circular queue

Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

   1: using System;

   2: using System.Text;

   3: using System.Threading;

   4:  

   5: public class IntegerQueue

   6: {

   7:     int[] _queue;

   8:     int _in;

   9:     int _out;

  10:     int _count;

  11:  

  12:     private static Object QueueLock = new Object(); // Make the Queue thread safe

  13:  

  14:     public IntegerQueue(int size)

  15:     {

  16:         Initialize(size);

  17:     }

  18:  

  19:     public void Initialize(int size)

  20:     {

  21:         _queue = new int[size];

  22:         _count = 0;

  23:         _in = 0;

  24:         _out = 0;

  25:     }

  26:  

  27:     public void Enqueue(int value)

  28:     {

  29:         lock (QueueLock)

  30:         {

  31:             Console.WriteLine("Enqueue: {0}", value);

  32:             if (_queue.Length <= _count)

  33:             {

  34:                 Console.WriteLine("Overflow.");

  35:             }

  36:             else

  37:             {

  38:                 _queue[_in] = value;

  39:                 _in = (_in + 1) % _queue.Length;

  40:                 _count++;

  41:             }

  42:             DebugPrint();

  43:         }

  44:     }

  45:     public int Dequeue()

  46:     {

  47:         lock (QueueLock)

  48:         {

  49:             Console.WriteLine("Dequeue:");

  50:             int value = 0;

  51:             if (_count <= 0)

  52:             {

  53:                 Console.WriteLine("Underflow.");

  54:             }

  55:             else

  56:             {

  57:                 value = _queue[_out];

  58:                 _out = (_out + 1) % _queue.Length;

  59:                 _count--;

  60:             }

  61:             DebugPrint();

  62:             return value;

  63:         }

  64:  

  65:     }

  66:     public override String ToString()

  67:     {

  68:         StringBuilder builder = new StringBuilder();

  69:         if (_count > 0)

  70:         {

  71:             for (int i = 0; i < _count; i++)

  72:             {

  73:                 builder.Append(_queue[(_out + i) % _queue.Length]);

  74:                 builder.Append(", ");

  75:             }

  76:         }

  77:         else

  78:         {

  79:             builder.Append("(empty)");

  80:         }

  81:         return builder.ToString();

  82:     }

  83:     public void DebugPrint()

  84:     {

  85:  

  86:         lock (QueueLock)

  87:         {

  88:             Console.WriteLine("\t{0}", ToString());

  89:         }

  90:  

  91:     }

  92:  

  93:  

  94:     public void QueueTest()

  95:     {

  96:         Enqueue(1);

  97:         Console.WriteLine();

  98:  

  99:         Enqueue(2);

 100:         Console.WriteLine();

 101:  

 102:        Enqueue(3);

 103:         Console.WriteLine();

 104:  

 105:         Console.WriteLine("--> {0}", Dequeue());

 106:         Console.WriteLine();

 107:  

 108:         Console.WriteLine("--> {0}", Dequeue());

 109:         Console.WriteLine();

 110:  

 111:         Console.WriteLine("--> {0}", Dequeue());

 112:         Console.WriteLine();

 113:  

 114:         Enqueue(4);

 115:         Console.WriteLine();

 116:  

 117:         Enqueue(5);

 118:         Console.WriteLine();

 119:  

 120:         Console.WriteLine("--> {0}", Dequeue());

 121:         Console.WriteLine();

 122:  

 123:         Enqueue(6);

 124:         Console.WriteLine();

 125:  

 126:         Enqueue(7);

 127:         Console.WriteLine();

 128:  

 129:         Enqueue(8);

 130:         Console.WriteLine();

 131:  

 132:         Enqueue(9);

 133:         Console.WriteLine();

 134:  

 135:         Console.WriteLine("--> {0}", Dequeue());

 136:         Console.WriteLine();

 137:  

 138:         Console.WriteLine("--> {0}", Dequeue());

 139:         Console.WriteLine();

 140:  

 141:         Console.WriteLine("--> {0}", Dequeue());

 142:         Console.WriteLine();

 143:  

 144:         Console.WriteLine("--> {0}", Dequeue());

 145:         Console.WriteLine();

 146:  

 147:         Console.WriteLine("--> {0}", Dequeue());

 148:         Console.WriteLine();

 149:  

 150:         Console.ReadLine();

 151:     }

 152:  

 153: }

 154:  

 155: public class QueueApp

 156: {

 157:     public static void Main(String[] args)

 158:     {

 159:         IntegerQueue queue = new IntegerQueue(5);

 160:  

 161:         Thread[] threads = new Thread[1];

 162:  

 163:         for (int i = 0; i < threads.Length; i++)

 164:         {

 165:             threads[i] = new Thread(new ThreadStart(queue.QueueTest));

 166:         }

 167:  

 168:         for (int i = 0; i < threads.Length; i++)

 169:         {

 170:             threads[i].Start();

 171:         }

 172:         Console.ReadLine();

 173:     }

 174: }

Triangle check

Write me a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function

 

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace Triangle

   7: {

   8:     class Program

   9:     {

  10:         public enum TriangleType

  11:         {

  12:             Scalene = 1,

  13:             Isosceles = 2,

  14:             Equilateral = 3,

  15:             Error = 4,

  16:         }

  17:         private static TriangleType triangle(int a, int b, int c)

  18:         {

  19:             TriangleType answer;

  20:  

  21:             if (a <= 0 || b <= 0 || c <= 0)

  22:             {

  23:                 // negative length -- illegal

  24:                 answer =  TriangleType.Error;

  25:             }

  26:             else if ((a + b <= c) || (b + c <= a) || (a + c <= b))

  27:             {

  28:                 // Sides can't possible connect -- illegal

  29:                 answer = TriangleType.Error;

  30:             }

  31:             else if ((a == b) && (b == c))

  32:             {

  33:                 // by the transitive rule, a == c well

  34:                 answer = TriangleType.Equilateral;

  35:             }

  36:             else if ((a == b) || (b == c) || (a == c))

  37:             {

  38:                 // We've already eliminated quilateral triangles above,

  39:                 // we'll only get here if exactly two sides match

  40:                 answer = TriangleType.Isosceles;

  41:             }

  42:             else

  43:             {

  44:                 // Since, we've eliminated all alternatives, we must have

  45:                 // a scalene triangle if we get here.

  46:                 answer = TriangleType.Scalene;

  47:             }

  48:  

  49:             return answer;

  50:         }

  51:  

  52:         static void Main(string[] args)

  53:         {

  54:             TriangleType result;

  55:             result = triangle(0, 0, 0);

  56:             Console.WriteLine("(0, 0, 0) = {0}", result.ToString());

  57:  

  58:             result = triangle(-1, 2, 3);

  59:             Console.WriteLine("(-1, 2, 3) = {0}", result.ToString());

  60:  

  61:             result = triangle(1, -2, 3);

  62:             Console.WriteLine("(1, -2, 3) = {0}", result.ToString());

  63:  

  64:             result = triangle(1, 2, -3);

  65:             Console.WriteLine("(1, 2, -3) = {0}", result.ToString());

  66:  

  67:             result = triangle(1, 1, 1);

  68:             Console.WriteLine("(1, 1, 1) = {0}", result.ToString());

  69:  

  70:             result = triangle(1, 2, 2);

  71:             Console.WriteLine("(1, 2, 2) = {0}", result.ToString());

  72:  

  73:             result = triangle(4, 5, 6);

  74:             Console.WriteLine("(4, 5, 6) = {0}", result.ToString());

  75:  

  76:             result = triangle(5, 1, 5);

  77:             Console.WriteLine("(5, 1, 5) = {0}", result.ToString());

  78:  

  79:             result = triangle(5, 5, 5);

  80:             Console.WriteLine("(5, 5, 5) = {0}", result.ToString());

  81:  

  82:             result = triangle(-10, -10, -10);

  83:             Console.WriteLine("(-10, -10, -10) = {0}", result.ToString());

  84:         }

  85:     }

  86: }

Merge 2 sorted Array in C#

using System;
using System.Linq;

namespace Merge2Array
{
class Program
{
static void Main()
{
int[] A = { 0, 3, 5, 6, 9, 10, 13, 14 }; // already sorted
int[] B = { 1, 2, 4, 6, 7, 11, 12, 15, 16 }; // ditto

// create sufficiently large output array
int[] C = new int[A.Length + B.Length];

// create indices to keep track of positions in B and C
int indexB = 0, indexC = 0;

// iterate through A
for (int i = 0; i < A.Length; i++)
{
// iterate through B ignoring elements already added to C
for (int j = indexB; j < B.Length; j++)
{
// if B contains elements which are smaller than the current element of A, add them to C
if (B[j] < A[i])
{
C[indexC++] = B[j];
indexB = j + 1; // value at which to start next iteration of B
}
else
{
// stop iterating when there are no more elements of B smaller than current element of A
break;
}
}
// now add current element of A to C
C[indexC++] = A[i];
// if this is A's final element but there are still larger items of B, add them to C
if (i == A.Length - 1 && indexB < B.Length)
{
for (int k = indexB; k < B.Length; k++) C[indexC++] = B[k];
}
}

// check it worked
for (int i = 0; i < C.Length; i++) Console.Write("{0} ", C[i]);
Console.WriteLine();

// Test do the same way by LINQ
int[] D = A.Concat(B).OrderBy(n => n).ToArray();

// check it worked again
for (int i = 0; i < D.Length; i++) Console.Write("{0} ", D[i]);
Console.WriteLine();

Console.ReadKey();
}
}
}



Is Palindrome in C#

using System;

namespace CheckStringForPalindrome
{
    class Program
    {
        public static bool IsPalindrome(string strValue)
       {
            int intLen, intStrPartLen;
            intLen = strValue.Length - 1;

            //Cut the length of the string into 2 halfs
            intStrPartLen = intLen / 2;
            for (int intIndex = 0; intIndex <= intStrPartLen; intIndex++)
            {
                //intIndex is the index of the char in the front of the string
                //Check from behind and front for match
                if (strValue[intIndex] != strValue[intLen])
                {
                    return false;
                }

                //decrease the lenght of the original string to
                //test the next Char from behind
                intLen--;
            }
            return true;
        }

        static void Main(string[] args)
        {
            string str;

            Console.Write("Please input:");
            str = Console.ReadLine();

            char[] strAry = str.ToCharArray();
            Array aStr = str.ToCharArray();
            Array.Reverse(aStr);
            string strreverse = string.Empty;
            foreach (char c in aStr) 
            { 
                strreverse = strreverse + c;
            }
            if (str.Equals(strreverse))
            {
                Console.WriteLine("String is poly" + System.Environment.NewLine);
            }
            else
            {
                Console.WriteLine("String is Not poly" + System.Environment.NewLine);
            }

        }
    }
}

Number to word in C#

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

namespace NumberToWord
{
public class NumberToWords{
string [] Number1 = {""," Hundrad"};
string [] Number2 = {"","One","Two", "Three","Four","Five"," Six"," Seven", "Eight"," Nine","Ten" };


public string Number(int number)
{
String str;
if (number % 100 < 10)
{
str = Number2[number % 100];
number /= 100;
}
else
{
str= Number2[number % 5];
number /= 5;
}

if (number == 0) return str;

return Number2[number] + "hundred" + str;

}

public String convert(int number) {
if (number == 0){
return "zero";
}
String pre = "";
String str1 = "";
int i = 0;
do {
int n = number % 100;
if (n != 0){
string s = Number(n);
str1 = s + Number1[i] + str1;
}
i++;
number /= 100;
}
while (number > 0);
return (pre + str1).Trim();
}

public static void Main(String[] args)
{
NumberToWords num = new NumberToWords();

Console.WriteLine("words is :=" + num.convert(0));
Console.WriteLine("words is :=" + num.convert(12));
Console.WriteLine("words is :=" + num.convert(9));
Console.WriteLine("words is :=" + num.convert(100));
}

} }

Make permutation

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

namespace Permutation2
{
class Program
{
private static void permutation(string str)
{
int length = str.Length;
bool[] used = new bool[length];

StringBuilder sb = new StringBuilder();
char[] arrChar = str.ToCharArray();

doPermute(arrChar, sb, used, length, 0);
}

private static void doPermute(char[] arrCh, StringBuilder sb, bool[] used, int length, int level)
{
if (level == length)
{
Console.WriteLine(sb.ToString());
return;
}

for (int i = 0; i < length; ++i)
{
if (used[i])
continue;

sb.Append(arrCh[i]);
used[i] = true;
doPermute(arrCh, sb, used, length, level + 1);
used[i] = false;
//sb.Capacity = sb.Length - 1;
sb.Remove(sb.Length - 1, 1);
}
}

static void Main(string[] args)
{
string sample = "abc";

Console.WriteLine("{0} : ", sample);
permutation(sample);

Console.ReadLine();

}
}
}

Convert String to Int & Int to String

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

namespace StringToLong
{
class StringToLong
{
private static int strToInt(string str)
{
int i = 0, num = 0;
bool isNeg = false;

int len = str.Length;

if (str[0] == '-')
{
isNeg = true;
i = 1;
}

while (i < len)
{
num *= 10;
num += (str[i++] - '0');
}
if (isNeg)
num *= -1;

return num;
}

private static string intToStr(int num)
{
int i = 0;
bool isNeg = false;

char[] temp = new char[10 + 1];

if (num < 0)
{
num *= -1;
isNeg = true;
}

//while (num != 0)
//{
// temp[i++] = (char)((num % 10) + '0');
// num /= 10;
//}

do
{
temp[i++] = (char)((num % 10) + '0');
num /= 10;

} while (num != 0);

StringBuilder sb = new StringBuilder();

if (isNeg)
sb.Append('-');

while(i > 0)
{
sb.Append( temp[--i]);
}
return sb.ToString();
}

private static long ConvertString(string str)
{
int len = str.Length;
bool blNegative = false;

int index = blNegative? 1:0;

if (str[0].Equals("-"))
{
blNegative = true;
}

long lnResult = 0;

do {
lnResult *= 10;
int i = str[index] - 48; //ASCII zero
if (i < 0 | i > 9)
throw new FormatException();

lnResult += i;
index++;
} while(len > index);

return blNegative? -lnResult:lnResult;
}

static void Main(string[] args)
{
string str1 = "3511";

Console.WriteLine(ConvertString(str1).ToString());

Console.WriteLine("{0} : {1}", str1, strToInt(str1).ToString());

str1 = "0";

Console.WriteLine("{0} : {1}", strToInt(str1), intToStr(strToInt(str1)));

Console.ReadLine();

}
}
}

Checking if a string has balanced parentheses

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

namespace isBalanced {
    class Program {

        const char LeftParenthesis = '(';
 const char RightParenthesis = ')';

        static bool isBalancedWithStack(string str) {
            
            if (str.Length <;= 1 || str.Equals(null))
                return false;

 var items = new Stack<int>(str.Length);
            int errorAt = -1;
 for (int i = 0; i < str.Length; i++)
            {
 
                if (str[i].Equals(LeftParenthesis))
                    items.Push(i);
 else if (str[i].Equals(RightParenthesis))
                {
                    if (items.Count == 0)
                    {
                        errorAt = i + 1;
 return false;
                    }
                    items.Pop();
 }
            }
            if (items.Count >; 0)
            {
                errorAt = items.Peek() + 1;
 return false;
            }
            return true;
 }


        static bool isBalancedWithoutStack(string str) {

            int count = 0;

 if (str.Length <= 1)
                return false;

 for (int i = 0; i < str.Length; i++)
            {
                if (str[i].Equals('('))
                    count++;
 else if (str[i].Equals(')'))
                {
                    count--;
 if (count < 0)
                        return false;
 }
            }

            return (count == 0);
 }

        static bool checkParentheses(string str) 
        {
            if (str.Length <;= 1)
                return false;

 int count = 0;

            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    case '(':
                        count++;
 break;

                    case ')':
                        count--;
 if (count < 0)
                            return false;
 break;
                }
            }

            return (count == 0);

 }

        static void Main(string[] args) {

            string[] arrSample = new string[] { " ", "", "(","()))))))", "(()((fff))())", "(()", "((((()))))", "(()(((())))())", "(()(((())))()", "()()()()()()()()()()()()" };



 for (int i = 0; i < arrSample.Length; i++)
            {
                if (isBalancedWithStack(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                if (isBalancedWithoutStack(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                if (checkParentheses(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                Console.WriteLine();
 }

        }
    }
}

 

Reverse the ordering of words in a string

I have this string s1 = “My name is X Y Z” and I want to reverse the order of the words so that s1 = “Z Y X is name My”.

I can do it using an additional array. I thought hard but is it possible to do it in place (without using additional data structures) and with the time complexity being O(n)?

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

namespace ReverseStringByWords
{
class Program
{

private static string ReverseAllWords(string str)
{
char[] in_text = str.ToCharArray();
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);

//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}

return new string(in_text);
}

private static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}

static void Main(string[] args)
{
// Original Sentence: My car is very fast
// Modifies Sentence: fast very is car My
string sample = "My car is very fast";

Console.WriteLine("{0} : {1}", sample, ReverseAllWords(sample));
Console.ReadLine();
}
}
}

2- Convert a String to long without using C#’s built in function?

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

namespace StringToInteger
{
class Program
{

private static int StrToInt(string str)
{
int intResult = 0;
int index = 0;
bool negative = false;
int len = str.Length;

if (str[0] == '-')
{
negative = true;
index = 1;
}

while (index < len)
{
intResult *= 10;
intResult += (str[index++] - '0');
}

if (negative)
intResult *= -1;

return intResult;
}

static void Main(string[] args)
{
string str1 = "-102990";

Console.WriteLine("{0} = {1}", str1, StrToInt(str1).ToString());

Console.ReadLine();
}
}
}

Testing website status

Like any applications, websites require a number of other components, such as the network and the operating system, in order to function. In the case of a problem you need to isolate the component causing the problem. One quick test is to see if the website is running. If you can confirm that it shows that the network and other components
are functioning.
PROBLEM
The phone rings. “The website isn’t available,” shouts the user. You need to check whether the website is up before performing other diagnostics.
SOLUTION
The following listing enables you to retrieve the website status,

$ws = DATA {
ConvertFrom-StringData -StringData @'
1 = Started
2 = Starting
3 = Stopped
4 = Stopping
5 = Unknown
'@
}
function get-websitestatus {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string]$computername="$env:COMPUTERNAME",
[string]$site

)
PROCESS{
if ($site) {
$sites = Get-WmiObject -Namespace 'root\webadministration' -Class Site -ComputerName $computername -Authentication 6 -Filter "Name='$site'"
}
else {
$sites = Get-WmiObject -Namespace 'root\webadministration' -Class Site -ComputerName $computername -Authentication 6
}
$data = @()

foreach ($site in $sites){
$wsdata = New-Object -TypeName PSobject
Add-Member -InputObject $wsdata -MemberType NoteProperty -Name "Name" -Value $site.Name

$state = $site.GetState()
Add-Member -InputObject $wsdata -MemberType NoteProperty -Name "Status" -Value $ws["$($state.ReturnValue)"]

$data += $wsdata
}
$data
}
}

Creating a website

You can create websites using the WMI provider, but there are some issues with performing this action due to Packet Privacy being enforced by the provider. This means you need to be a little bit sneaky in the way you approach this problem. I don’t recommend this approach for all use of WMI, but it’s a useful fallback technique if you can’t work directly with the WMI cmdlets.

 

function new-website {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string]$computer="$env:COMPUTERNAME",
[parameter(Mandatory=$true)]
[string]$site,
[parameter(Mandatory=$true)]
[string]$domain,
[parameter(Mandatory=$true)]
[string]$dirpath
)
PROCESS{
$conopt = New-Object System.Management.ConnectionOptions
$conopt.Authentication = [System.Management.AuthenticationLevel]::PacketPrivacy

$scope = New-Object System.Management.ManagementScope
$scope.Path = "\\$computer\root\WebAdministration"
$scope.Options = $conopt

$path = New-Object System.Management.ManagementPath
$path.ClassName = "Site"

$website = New-Object System.Management.ManagementClass($scope, $path, $null)

$path2 = New-Object System.Management.ManagementPath
$path2.ClassName = "BindingElement"

$bind = New-Object System.Management.ManagementClass($scope, $path2, $null)
$BInstance = $bind.CreateInstance()

$Binstance.BindingInformation = "*:80:$site.$domain"
$BInstance.Protocol = "http"

$website.Create($site, $Binstance, $dirpath, $true)
}
}

Online References for implementing checklist

 

C# Performance:
Microsoft:
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx
http://msdn.microsoft.com/en-us/library/ff647813.aspx
http://msdn.microsoft.com/en-us/library/ms973839.aspx
http://msdn.microsoft.com/en-us/library/ms973839
http://msdn.microsoft.com/en-us/library/ms973852
http://msdn.microsoft.com/en-us/magazine/cc163510.aspx
http://msdn.microsoft.com/library/ms973837.aspx
http://msdn.microsoft.com/library/ms973858.aspx

Others:
http://www.techgalaxy.net/Docs/Dev/5ways.htm
http://www.codeproject.com/KB/cs/effective1.aspx

Blogs:
http://blogs.msdn.com/b/ricom/

ASP .Net Performance:
http://msdn.microsoft.com/en-us/magazine/cc163854.aspx
http://msdn.microsoft.com/en-us/library/ff647787.aspx
http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx
http://www.realsoftwaredevelopment.com/20-tips-to-improve-aspnet-application-performance/
http://wiki.asp.net/page.aspx/31/performance/

WCF Performance:
http://support.microsoft.com/kb/982897
http://msdn.microsoft.com/en-us/library/ee377061(v=bts.10).aspx
http://msdn.microsoft.com/en-us/library/ms735098.aspx

Blogs:
http://www.askives.com/wcf-performance.html
http://blog.thekieners.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/
http://merill.net/2008/10/wcf-performance-optimization-tips/
http://weblogs.asp.net/sweinstein/archive/2009/01/03/creating-high-performance-wcf-services.aspx
http://metallemon.hubpages.com/hub/WCF-Service-Performance
http://www.aspnet101.com/2010/08/wcf-performance-best-practices/
http://blogs.msdn.com/b/stcheng/archive/2011/01/05/wcf-wcf-performance-testing-information-share.aspx
http://webservices20.blogspot.com/2009/01/wcf-performance-gearing-up-your-service.html
http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx

MVC Performance:
http://www.codeproject.com/KB/aspnet/How_to_improve_performanc.aspx
http://weblogs.asp.net/gunnarpeipman/archive/2010/02/07/asp-net-mvc-performance-ii-optimizing-resources.aspx
http://www.slideshare.net/rudib/aspnet-mvc-performance
http://msmvps.com/blogs/kenlin/archive/2010/05/14/mvc-performance-in-iis-part-ii.aspx
http://blogs.msdn.com/b/marcinon/archive/2011/02/07/mvc-performance-tips.aspx

Thread Safe code

Thread-safety is a computer programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous execution by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. It was once only a concern of the operating system programmer but has of late become a commonplace issue to be tackled by the everyday programmer. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least astonishment. Thread-safety is a property aimed for so as to minimize surprising behavior by re-establishing some of the correspondences between the actual flow of control and the text of the program.

The requirement for thread-safety highlights the inherent tension in multi-threaded programming: the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:

  • Accessing global variables or the heap.
  • Allocating/freeing resources that have global limits (files, sub-processes, etc.)
  • Indirect accesses through handles or pointers

A subroutine that only uses variables from the stack, depends only on the arguments passed in, and calls other subroutines with similar properties is reentrant, and thus thread-safe.

As seen in the definition, there are a few ways to achieve thread-safety:

  • Reentrancy: Basically, writing code in such a way as to avoid sharing of data across threads.
  • Mutual exclusion: Access to shared data is serialized using mechanisms that ensure only one thread is accessing the shared data at any time. If a piece of code accesses multiple shared pieces of data, there needs to be an enormous amount of care in using mutual exclusion mechanisms — problems include race conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.

A commonly used idiom combines both approaches:

  • Make changes to a private copy of the data, and finally, atomically update the shared data from the private copy. Thus, most of the code would be close to re-entrant, and the amount of time spent serialized would be small.

The concept of exception safety is closely related, since it again deals with (synchronous) flows of control not directly correlated to the text of a program.

Convert a String to long without using C#’s built in function?

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

namespace StringToLong
{
class StringToLong
{
private static long ConvertString(string str)
{
int len = str.Length;
bool blNegative = false;

int index = blNegative? 1:0;

if (str[0].Equals("-"))
{
blNegative = true;
}

long lnResult = 0;

do {
lnResult *= 10;
int i = str[index] - 48; //ASCII zero
if (i < 0 | i > 9)
throw new FormatException();

lnResult += i;
index++;
} while(len > index);

return blNegative? -lnResult:lnResult;
}

static void Main(string[] args)
{
string str1 = "35111111111";

Console.WriteLine(ConvertString(str1).ToString());

Console.ReadLine();

}
}
}

In Java

public static void main(String[] args) {
String s = "35";
long ans = parse(s);
}

public final static long parse(CharSequence d) {
int l = d.length();
boolean n= d.charAt(0) == '-';
long v = 0;
int p = n?1:0;
do {
v *= 10;
int i = d.charAt(p) - 48;
if (i < 0 | i > 9)
throw new NumberFormatException(d+"");
v += i;
p++;
} while (l > p);
return n?-v:v;
}