Monday, August 17, 2015

Hackerrank : Caeser Cipher in C#

//caeser cipher
int n = Convert.ToInt32(Console.ReadLine());

string s = Console.ReadLine();

int offset = Convert.ToInt32(Console.ReadLine());

char[] final = new char[n];

for (int i = 0; i < n; i++)



{
//bool ischar = false;

bool isSmall = false;

int curchar = (int)s[i];

if(curchar >= 97 && curchar <= 122)



{
isSmall = true;



curchar = curchar - 32;

}
if (curchar >= 65 && curchar <= 90)



{
int newChar = curchar + offset;

while(newChar >90)


{ newChar = newChar - 26; }
final[i] = isSmall ? (char)(newChar + 32) : (char)(newChar);

Console.Write(final[i]);



}
else



{

final[i] = s[i];
Console.Write(final[i]);



}

}
Console.ReadLine();

Find if 2 strings are anagram or not

/* find if 2 strings are anagram or not like silent and listen*/
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
bool isAnagram = true;
int strLen = str1.Length;
int[] arr = new int[256];
if(strLen == str2.Length)
{
for (int i = 0; i < strLen; i++)
{
arr[(int)str1[i]]++;
arr[(int)str2[i]]--;
}
foreach (int i in arr)
{
if (i > 0)
{
isAnagram = false;
break;
}
}
}
else
{
isAnagram = false;
}

Linked list: Pairwise swap

private static void SwapEveryTwoNodes(LinkedList l)
        {
            if (l == null || l.head == null)
                return;
            Node cur = l.head;
            Node next = cur.next;
            Node pre = null;
            if (cur == null || next == null)
                return;
            l.head = l.head.next;
            //in every iteration, there should be minimum 3 pointer change. Before next iteration begins,
            //ensure that the pointer to previos node is saved.           
          
            while (cur != null && next != null)
            {
                // cur =1, next = 2
                cur.next = next.next; //1.next=3
                next.next = cur; // 2.next=1
                if(pre!=null) // this check is only for first iteration
                    pre.next = next; //connect the left side of the LL with the swapped nodes
                pre = cur; //Save previous step
                cur = cur.next; //next odd numbered node
                next = cur!=null? cur.next:null; //next even numbered node              
            }
        }