Implement IndexOf method without Framework

Array.IndexOf searches an array. It acts upon an array of any type in the C# language. It locates the offset of the value searched for. The IndexOf method on Array, in both its generic form and its LastIndexOf form, is useful in many program contexts.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IndexOF

   7: {

   8:     class Program

   9:     {

  10:  

  11:         private static int IndexOf(char[] chars1, char[] chars2)

  12:         {

  13:             if (chars1.Length < chars2.Length)

  14:                 return -1;

  15:  

  16:             int found = -1;

  17:             int j = 0;

  18:  

  19:             for (int i = 0; i < chars1.Length; i++)

  20:             {

  21:                 if (chars1[i] == chars2[j])

  22:                 {

  23:                     if (j == 0)

  24:                         found = i;

  25:  

  26:                     j++;

  27:                     if (j >= chars2.Length)

  28:                         return found;

  29:                 }

  30:                 else

  31:                 {

  32:                     j = 0;

  33:  

  34:                     if (found >= 0)

  35:                         i = found;

  36:                     found = -1;

  37:                 }

  38:             }

  39:             

  40:             return -1;

  41:         }

  42:  

  43:         static void Main(string[] args)

  44:         {

  45:             char[] arr1 = { 'v', 'a', 'b', 'c', 'd', 'e', 'f' };

  46:             char[] arr2 = { 'c', 'd', 'v'};

  47:  

  48:  

  49:             Console.WriteLine("index = {0}", IndexOf(arr1, arr2).ToString());

  50:  

  51:             Console.ReadKey();

  52:         }

  53:     }

  54: }

Advertisements

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: }

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: }

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:
/\*.*?\*/

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();
}
}
}

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;
}

How to Reverse a String

Question: given a string, reverse it. You can destroy the original string or return a new string that is the reverse of the original string. For example, if input is “abcde”, output will be “edcba”.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:

   6: namespace ReverseString {

   7:

   8:     static class StringExtensions {

   9:         public static string Reverse(this string input) {

  10:             return new string(input.ToCharArray().Reverse().ToArray());

  11:         }

  12:     }

  13:

  14:     class Program {

  15:

  16:         static void ReverseString(string str) {

  17:             if (str.Length == 0)

  18:             {

  19:                 Console.WriteLine("False");

  20:                 return;

  21:             }

  22:             StringBuilder stb = new StringBuilder();

  23:

  24:             for (int i = str.Length - 1; i > -1; i--)

  25:             {

  26:                 stb.Append(str[i]);

  27:             }

  28:

  29:             Console.WriteLine("{0} => {1}", str, stb.ToString());

  30:

  31:         }

  32:

  33:         static void Main(string[] args) {

  34:

  35:

  36:             Console.WriteLine("hello world".Reverse());

  37:

  38:             ReverseString("This is a book.");

  39:

  40:             Console.WriteLine("...end");

  41:             Console.ReadLine();

  42:         }

  43:     }

  44: }

How to determine if two strings are anagrams?

First of all, what are anagrams? Well, anagrams are words that have the same characters which can be at different locations in the words. For example, “level” and “level” are anagrams, a special kind of anagrams because they are exactly the same in terms of characters and their locations in the words. Moreover, “rat” and “art” are also anagrams because all characters in “rat” are in “art”, no more no less. Another example is “seek” and “ekes”. Pay attention to the numbers of “e” letters in both words, they must be the same amount too. Thus, “seek” and “sek” are not anagrams.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:

   6: namespace areAnagrams {

   7:     class Program {

   8:         static bool areAnagrams(string str1, string str2) {

   9:             if (str1.Length != str2.Length)

  10:             {

  11:                 return false;

  12:             }

  13:

  14:             int[] charsTracker = new int[26];

  15:

  16:             for (int i = 0; i < str1.Length; i++)

  17:             {

  18:                 charsTracker[str1[i] - 'a']--;

  19:                 charsTracker[str2[i] - 'a']++;

  20:             }

  21:

  22:             for (int i = 0; i < 26; i++)

  23:             {

  24:                 if (charsTracker[i] != 0)

  25:                     return false;

  26:             }

  27:

  28:             return true;

  29:         }

  30:

  31:         static void Main(string[] args) {

  32:

  33:             if (areAnagrams("abcxyz", "zyxcba"))

  34:                 Console.WriteLine("True");

  35:             else

  36:                 Console.WriteLine("False");

  37:

  38:         }

  39:     }

  40: }

Explanation:

  1. First we check to see if the two strings have the same length. If not, they are not anagrams.
  2. Then, we declare an array of 26 integers. We will use this array to keep track of the characters in both strings. Why 26? You may ask. It is because we have 26 letters in the alphabet. Each of the letter is represented by an index in the array. And the value stored in each index represents the count of the letter’s occurrence in both words.
  3. Next, we just loop through the strings and count the number of occurrences for each letter in both strings. For every letter in the first string, we’ll subtract 1 from the count value stored in the index representing that letter. On the other hand, we’ll add 1 for every letter in the second string. By doing this, we know that if both strings have the same letters, the final result will always be 0 because they cancel each other out through decrement and increment.
  4. Lastly, we check the array of counts. If any index has a non-zero value, then the strings are not anagrams

We’ll do an example by checking for “rat” and “art”. First run of the loop, “r” count is -1 because it is in first string and “a” count is 1 because it is in second string. Second run, “a” count is now 0 because it appears in the first string so 1 – 1 is 0. Moreover, “r” count is also 0 because it appears in the second string -1 + 1 = 0. Last run, “t” count is 0 because it appears in both strings 1 – 1 = 0. Thus, we know “rat” and “art” are anagrams because the resulting array contains all 0s

Kinect for Windows SDK Hardware and Software Requirements

Unlike other Kinect libraries, the Kinect for Windows SDK, as its name suggests, only runs on Windows operating systems. Specifically, it runs on x86 and x64 versions of Windows 7. It has been shown to also work on early versions of Windows 8. Because Kinect was designed for Xbox hardware, it requires
roughly similar hardware on a PC to run effectively.

Hardware Requirements
• Computer with a dual-core, 2.66-GHz or faster processor
• Windows 7–compatible graphics card that supports Microsoft DirectX 9.0c
capabilities
• 2 GB of RAM (4 GB or RAM recommended)
• Kinect for Xbox 360 sensor
• Kinect USB power adapter
Use the free Visual Studio 2010 Express or other VS 2010 editions to program against the Kinect for Windows SDK. You will also need to have the DirectX 9.0c runtime installed. Later versions of DirectX are not backwards compatible. You will also, of course, want to download and install the latest version of the Kinect for Windows SDK. The Kinect SDK installer will install the Kinect drivers, the Microsoft Research Kinect assembly, as well as code samples.

Software Requirements
• Microsoft Visual Studio 2010 Express or other Visual Studio 2010 edition:
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express
• Microsoft .NET Framework 4
• The Kinect for Windows SDK (x86 or x64): http://www.kinectforwindows.com
• For C++ SkeletalViewer samples:
• DirectX Software Development Kit, June 2010 or later version:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=6
812
• DirectX End-User Runtime Web Installer:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=35

Check if strings are anagrams using LINQ–C#

 

The approach in this article shows the use of LINQ to group by array elements and comparing two strings. The underlying algorithm is the traditional approach of sorting the characters in the strings and then comparing the strings. However the more efficient implementation of anagram checking could be done by using hash tables or dictionaries.

   1:  

   2: using System;

   3: using System.Collections.Generic;

   4: using System.Linq;

   5: using System.Text;

   6:  

   7: namespace AnagramCheck

   8: {

   9:     public class AnagramChecker

  10:     {

  11:         public bool IsAnagram(string[] anagrams)

  12:         {

  13:             var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());

  14:  

  15:             foreach (var group in orderGroups)

  16:             {

  17:                 if (group.Count() == anagrams.Length)

  18:                 {

  19:                     return true;

  20:                 }

  21:             }

  22:             return false;

  23:         }

  24:     }

  25:  

  26:     public class AnagramEqualityComparer : IEqualityComparer<string>

  27:     {

  28:         public bool Equals(string x, string y)

  29:         {

  30:             return getCanonicalString(x) == getCanonicalString(y);

  31:         }

  32:  

  33:         public int GetHashCode(string obj)

  34:         {

  35:             return getCanonicalString(obj).GetHashCode();

  36:         }

  37:  

  38:         private string getCanonicalString(string word)

  39:         {

  40:             char[] wordChars = word.ToCharArray();

  41:             Array.Sort<char>(wordChars);

  42:             return new string(wordChars);

  43:         }

  44:     }

  45: }

Creating a Hash Code for a Data Type

Problem
You have created a class or structure that will be used as a key in a Hashtable or Dictionary<T,U>. You need to overload the GetHashCode method in order to return a good distribution of hash values (the Discussion section defines a good distribution of hash values). You also need to choose the best hash-code algorithm to use in the GetHashCode method of your object.

        public static void CreateHashCodeDataType()
        {
            SimpleClass simpleClass = new SimpleClass("foo");

            Hashtable hashTable = new Hashtable();
            hashTable.Add(simpleClass, 100);

            Dictionary<SimpleClass, int> dict = new Dictionary<SimpleClass, int>();
            dict.Add(simpleClass, 100);
        }

        public class SimpleClass
        {
            private string text = "";

            public SimpleClass(string inputText)
            {
                text = inputText;
            }

            public override int GetHashCode()
            {
                return (ShiftAndAddHash(text));
            }

            public int ShiftAndAddHash(string strValue)
            {
                int hashCode = 0;

                foreach (char c in strValue)
                {
                    hashCode = (hashCode << 5) + (int)c + (hashCode >> 2);
                }

                return (hashCode);
            }
        }

        public int SimpleHash(params int[] values)
        {
            int hashCode = 0;
            if (values != null)
            {
                foreach (int val in values)
                {
                    hashCode ^= val;
                }
            }

            return (hashCode);
        }

        public int FoldingHash(params long[] values)
        {
            int hashCode = 0;
            if (values != null)
            {
                int tempLowerVal = 0;
                int tempUpperVal = 0;
                foreach (long val in values)
                {
                    tempLowerVal = (int)(val & 0x000000007FFFFFFF);
                    tempUpperVal = (int)((val >> 32) & 0xFFFFFFFF);
                    hashCode^= tempLowerVal ^ tempUpperVal;
                }
            }

            return (hashCode);
        }

        public int ContainedObjHash(params object[] values)
        {
            int hashCode = 0;
            if (values != null)
            {
                foreach (int val in values)
                {
                    hashCode ^= val.GetHashCode();
                }
            }

            return (hashCode);
        }

        public int CryptoHash(string strValue)
        {
            int hashCode = 0;
            if (strValue != null)
            {
                byte[] encodedUnHashedString = 
                    Encoding.Unicode.GetBytes(strValue);

                byte[] key = new byte[16];
                RandomNumberGenerator.Create().GetBytes(key);

                MACTripleDES hashingObj = new MACTripleDES(key);
                byte[] code = 
                    hashingObj.ComputeHash(encodedUnHashedString);

                // use the BitConverter class to take the 
                // first 4 bytes and use them as an int for
                // the hash code
                hashCode = BitConverter.ToInt32(code,0);    
            }

            return (hashCode);
        }

        public int CryptoHash(long intValue)
        {
            int hashCode = 0;
            byte[] encodedUnHashedString = 
                Encoding.Unicode.GetBytes(intValue.ToString());

            SHA256Managed hashingObj = new SHA256Managed();
            byte[] code = hashingObj.ComputeHash(encodedUnHashedString);

            // use the BitConverter class to take the 
            // first 4 bytes and use them as an int for
            // the hash code
            hashCode = BitConverter.ToInt32(code,0);    

            return (hashCode);
        }

        public int ShiftAndAddHash (string strValue)
        {
            int hashCode = 0;
            
            foreach (char c in strValue)
            {
                hashCode = (hashCode << 5) + (int)c + (hashCode >> 2);
            }
            
            return (hashCode);
        }

        public int CalcHash(short someShort, int someInt, long someLong,
            float someFloat, object someObject)
        {
            int hashCode = 7;
            hashCode = hashCode * 31 + (int)someShort;
            hashCode = hashCode * 31 + someInt;
            hashCode = hashCode * 31 + 
                (int)(someLong ^ (someLong >> 32));
            long someFloatToLong = (long)someFloat;
            hashCode = hashCode * 31 + 
                (int)(someFloatToLong ^ (someFloatToLong >> 32));

            if (someObject != null)
            {
                hashCode = hashCode * 31 + 
                    someObject.GetHashCode();
            }

            return (hashCode);
        }

        public int ConcatStringGetHashCode(int[] someIntArray)
        {
            int hashCode = 0;
            StringBuilder hashString = new StringBuilder();

            if (someIntArray != null)
            {
                foreach (int i in someIntArray)
                {
                    hashString.Append(i.ToString() + "^");
                }
            }
            hashCode = hashString.GetHashCode();

            return (hashCode);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }