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