Thursday 30 June 2016

Convert InFix Expression to PostFix Expression using stacks

InFix Expression to PostFix Expression using stacks   :

import java.util.Scanner;
import java.util.Stack;

public class InfixToPostFix {
    public static void main(String args[]) {
        Stack<Character> stack = new Stack<Character>();
        Scanner sc = new Scanner(System.in);
        // Read InFix String
        char inFixArray[] = sc.next().toCharArray();
        String postFixString = "";
        for (char e : inFixArray) {
            // check for operand
            if (e >= 'A' && e <= 'Z') {
                postFixString = postFixString + e;
            } else if (e >= 'a' && e <= 'z') {
                postFixString = postFixString + e;
            } else if (e == '(') {
                stack.push(e);
            } else if (e == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    postFixString = postFixString + stack.pop();
                }
                stack.pop();
            } else {
                // check for operator
                while (!stack.isEmpty() && Prec(stack.peek()) >= Prec(e)) {
                    postFixString = postFixString + stack.pop();
                }
                stack.push(e);

            }
        }
        while (stack.isEmpty()) {
            postFixString = postFixString + stack.pop();
        }
        System.out.println(postFixString);

    }

    static int Prec(char e) {
        switch (e) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;

        case '^':
            return 3;

        }
        return -1;
    }
}

Wednesday 29 June 2016

Evaluate PostFix Expression using stack

Evaluate PostFix Expression using stack   :

import java.util.Scanner;
import java.util.Stack;

public class EvalPostFix {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Stack<Integer> stack = new Stack<Integer>();
        char exp[] = sc.next().toCharArray();
        for (char e : exp) {
            if (Character.isDigit(e)) {
                stack.push(Character.getNumericValue(e));
            } else {
                int var1 = stack.pop();
                int var2 = stack.pop();
                switch (e) {
                case '+':
                    stack.push((var1 + var2));
                    break;
                case '-':
                    stack.push((var1 - var2));
                    break;
                case '*':
                    stack.push((var1 * var2));
                    break;
                case '/':
                    stack.push((var1 / var2));
                    break;
                }

            }
        }
        System.out.println("" + stack.peek());

    }

}
 

Reverse String using Stack Data Structure

 Reverse a String using Stack Data Structure in Java  :


import java.util.Stack;

public class ReverseString {
    public static void main(String args[]) {
        Stack<Character> stack = new Stack<Character>();
        String result="My name is Anurag Goel.";
        char exp[] = obj.next().toCharArray();
        for (char e : exp) {
            stack.push(e);
        }
        while (!stack.isEmpty()) {
            result=result+stack.pop().toString();
        }
        System.out.println(result);
    }

}

Stack Implementation using LinkedList

Stack Implementation using LinkedList in Java     :

import java.util.*;

public class DynamicStack {
 static class Node {
  int data;
  Node next;
  Node(int e) {
   this.data = e;
   this.next = null;
  }
 }
 LinkedList < Node > list;
 DynamicStack() {
  this.list = new LinkedList < Node > ();
 }
 public void push(int data) {
  list.add(new Node(data));
 }
 public int pop() {
  if (list.size() < 1)
   return -1;
  return list.remove().data;
 }
 public int Top() {
  return list.getLast().data;
 }
 public boolean isEmpty() {
  return list.size() < 1 ? true : false;
 }
 public static void main(String[] args) {
  DynamicStack stack = new DynamicStack();
  stack.push(1);
  stack.push(2);
  stack.push(3);
  stack.push(4);
  stack.push(5);
  while (!stack.isEmpty()) {
   System.out.println(stack.pop());
  }

 }
}

Stack Implementation

Stack Implementation in Java :
Following example shows how to implement stack in Java .

/**
 *
 * @author Anurag
 *
 *
 */
public class ArrayStack{

    private int array[];
    private int top;
    private int capacity;

ArrayStack(int capacity)
{
    this.capacity=capacity;
    this.array=new int[capacity];
    top=-1;
}
public boolean isEmpty()
{
    return top==-1?true:false;
}
public boolean isFull()
{
    return top==capacity-1?true:false;
}
public int Top()
{
    if (top==-1)
    {
        System.out.println("Stack is Empty");
    return -1;
}
    return array[top];
}

public void push(int e)
{
    if (top==capacity-1)
    {
        System.out.println("Stack is Full !");
        return;
    }
    array[++top]=e;
    return;
}

public int pop()
{
    if (top==-1)
    {
        System.out.println("Stack is Empty !");
        return -1;
    }
    return array[top--];
}
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);stack.push(6);
        System.out.println("Stack is Full :: "+stack.isFull());
        while(!stack.isEmpty())
        {
            System.out.println(""+stack.pop());
        }
        System.out.println("Stack is Empty :: "+stack.isEmpty());

    }
}

Hackerrank , 30 Days of Code Challenges ( Day 19 Solution)


 Day 19: Interfaces   :


//Write your code here
class Calculator implements AdvancedArithmetic
    {

    public int divisorSum(int n)
        {
        int sum=0;
        for(int i=1 ; i<=n;i++)
            {
            if(n%i==0)
                sum+=i;
        }
        return sum;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 20 Solution)

Day 20: Sorting   :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }


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

            for (int j = 0; j < n - 1; j++) {
                 if (a[j] > a[j + 1]) {
                   int temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                    numberOfSwaps++;
                }
            }
            if (numberOfSwaps == 0) {
                break;
            }
        }

        System.out.println("Array is sorted in "+numberOfSwaps+" swaps.");
        System.out.println("First Element: "+a[0]);
        System.out.println("Last Element: "+a[a.length-1]);
    }


}

Tuesday 28 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 18 Solution)

 Day 18: Queues and Stacks   :

public class Solution {
    // Write your code here.
    Stack<Character> stack = new Stack<Character>();
    Queue<Character> queue = new LinkedList<Character>();
    void pushCharacter(char ch)
        {
        stack.push(ch);
    }
     void enqueueCharacter(char ch){
        queue.add(ch);
     }
    char popCharacter() {
        return stack.pop();
    }

    char dequeueCharacter()
        {
        return queue.remove();
    }

Hackerrank , 30 Days of Code Challenges ( Day 16 & Day 17 Solutions)

Day 16: Exceptions - String to Integer    :
 import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try{
        String S = in.next();
            System.out.println(""+Integer.parseInt(S));
    }catch(Exception e)
            {
            System.out.println("Bad String");
        }
    }
}

Day 17: More Exceptions   :
class Calculator :
    def power(self, a, b):
        if a>= 0 and b>=0:
            return a**b
        else:
            return "n and p should be non-negative"
 

Hackerrank , 30 Days of Code Challenges ( Day 13 - 15 Solutions)

Day 13: Abstract Classes   :
 
//Write MyBook Class
class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Day 14: Scope   :

    # Add your code here
    def computeDifference(self):
        self.maximumDifference =  max(a)-min(a)


Day 15: Linked List   :
 class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 12 Solution)

 Day 12: Inheritance    :

class Student extends Person{
    private int[] testScores;
    Student(String firstName, String lastName, int identification , int [] scores)
        {
        super(firstName,lastName,identification );
        this.testScores=scores;
    }

    public String calculate()
        {
        int sum =0;
        for(int i : this.testScores)
            {
            sum+=i;
        }
        double avg= sum/testScores.length;
        if (avg<=100 && avg>=90)
            {
            return "O";
        }else if(avg<90 && avg>=80)
            {
             return "E";
        }
        else if(avg<80 && avg>=70)
            {
             return "A";
        }
        else if(avg<70 && avg>=55)
            {
             return "P";
        }
         else if(avg<55 && avg>=40)
            {
             return "D";
        }
        else{
             return "T";
        }
    }

}

Hackerrank , 30 Days of Code Challenges ( Day 10 & Day 11 Solutions)

Day 10: Binary Numbers    :

import sys
n = int(raw_input().strip())
string = '{0:b}'.format(n)
array=string.split('0')
array.sort()
print len(array[len(array)-1])

Day 11: 2D-Arrays    :
arr = []
max=-999
for arr_i in xrange(6):
   arr_temp = map(int,raw_input().strip().split(' '))
   arr.append(arr_temp)

for i in xrange(4):
    for j in xrange(4):
        temp=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
    if temp > max:
        max=temp

print max

Friday 24 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 6-9 Solutions)

Day 6: Let's Review  :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
for i in range(0,t):
    string =raw_input()
    print ''.join([string[i] for i in range(0,len(string),2)])+" "+''.join([string[i] for i in range(1,len(string),2)])

Day 7: Arrays   :
#!/bin/python
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
print " ".join(str(i) for i in arr)

Day 8: Dictionaries and Maps     :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
data=dict()
index=[]
for i in range(0,t):
    array=raw_input().split(" ")
    data[array[0]]=array[1]
for k in range(0,t):
    inp= raw_input()
    if data.has_key(inp):
        print inp+"="+data[inp]
    else:
        print "Not found"

Day 9: Recursion    :
n= input()
def factorial(n):
    if n ==0 or n==1 :
        return 1
    else:
        return n*factorial(n-1)
print factorial(n)





Saturday 18 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 0-5 Solutions)

Hackerrank , 30 Days of Code Challenges  =>

Day 0: Hello, World (Python) :

inputString = raw_input() # get a line of input from stdin and save it to our variable

# Your first line of output goes here
print 'Hello, World.'

# Write the second line of output
print inputString

Day 1: Data Types (C#) :

// Declare second integer, double, and String variables.
        int i2;
        double d2;
        string s2;
       
        // Read and save an integer, double, and String to your variables.
        i2=int.Parse(Console.ReadLine());
        d2= double.Parse(Console.ReadLine());
        s2 = Console.ReadLine();
       
        // Print the sum of both integer variables on a new line.
        Console.WriteLine("{0:#.#}",i2+i);
       
        // Print the sum of the double variables on a new line.
        Console.WriteLine("{0:0.0}",d+d2);
        // Concatenate and print the String variables on a new line
        // The 's' variable above should be printed first.
        Console.WriteLine(s+s2);

Day 2: Operators (Python) :

a=raw_input()
b=raw_input()
c=raw_input()
print "The total meal cost is "+str(int(round(float(a)+(float(b)*float(a)/100)+(float(c)*float(a)/100))))+" dollars."


Day 3: Intro to Conditional Statements (Python) :

 #!/bin/python

import sys


N = int(raw_input().strip())

if N%2!=0:
    print "Weird"
elif N>=2 and N<=5 :
    print "Not Weird"
elif N>=6 and N<=20 :
    print "Weird"
else:
    print "Not Weird"
    

Day 4: Class vs. Instance (Java) :

public class Person {
    private int age;   
 
    public Person(int initialAge) {
          // Add some more code to run some checks on initialAge
        this.age=initialAge;
    }

    public void amIOld() {
          // Write code determining if this person's age is old and print the correct statement:
        if(this.age<0)
          { System.out.println("Age is not valid, setting age to 0.");
           this.age=0;
           amIOld();
          }
        else if(this.age<13)
            System.out.println("You are young.");
        else if(this.age<18)
            System.out.println("You are a teenager.");
        else if(this.age>=18)
            System.out.println("You are old.");
    }

    public void yearPasses() {
          // Increment this person's age.
        this.age+=1;
    }

Day 5: Loops (Python) :

#!/bin/python

import sys


N = int(raw_input().strip())
for i in xrange(1,11):
    print str(N)+" x "+str(i)+" = "+str(N*i)

Friday 17 June 2016

Merge two sorted Linked List

 Merge 2 Sorted LinkedList :

class MergeLinkedList
{
  static class Node
  {
    int data;
    Node next;
  }
  public static void main(String[] args) {
    Node head1 = new Node();
    Node head2=  new Node();
    Node head3=  new Node();
    head3=null;
    head1.data=0;
    head2.data=1;
    head1=insert(insert(insert(insert(insert(insert(head1,2),5),7),8),9),11);
    head2=insert(insert(insert(insert(insert(head2,2),6),8),11),13);
    while(true)
    {
      if(head1==null && head2==null)
      {
        break;
      }
      else if(head1==null)
      {
        head3=insert(head3,head2.data);
        head2=head2.next;
      }
      else if(head2==null)
      {
        head3=insert(head3,head1.data);
        head1=head1.next;
      }
      else if(head1.data<=head2.data)
      {
        head3=insert(head3,head1.data);
          head1=head1.next;
      }
      else{
        head3=insert(head3,head2.data);
          head2=head2.next;
      }
    }
    printList(head3);
  }

  public static Node insert(Node head, int data) {
   Node node = new Node();
   node.data = data;
   node.next = null;
      if(head==null)
      return node;
 Node currentNode= head;
 while(currentNode.next!=null)
 {
     currentNode=currentNode.next;
     }

   currentNode.next=node;
   return head;
  }

 /**
  * Print All Elements of Linked List
  *
  * @param      node  The node
  */
  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }

}
}

Thursday 16 June 2016

Delete Nth Node From Linked List

Delete Nth Node  From Linked List : 

class DeleteNthNode
{
  static class Node {
   int data;
   Node next;
  }
  /**
  @main Method
  **/
  public static void main(String[] args) {
  Node head = insert(insert(insert(insert(null, 1), 2), 3),4);
  head= delete(head,0);
  head= delete(head,2);
  printList(head);

  }
  /**
   * Delete Node At Nth Position of Linked List
   *
   * @param      head  The head
   *
   * @param      Nth Position
   * @return     return head of Linked List
   */
  public static Node delete(Node head,int pos) {
   if (head == null) {
    return head;
   }
   if(pos==0)
   {
     Node next = head.next;
     return next;
   }
   else{
     Node currentNode=head;
     while((pos-1)>0)
     {
       currentNode=currentNode.next;
       pos--;
     }
    Node next = currentNode.next.next;
    currentNode.next=next;
    return head;
   }

  }

  /**
   * Insert Node at End
   *
   * @param      head  The head node
   * @param      data  The data
   *
   * @return     { description_of_the_return_value }
   */
   public static Node insert(Node head, int data) {
    Node node = new Node();
    node.data = data;
    node.next = null;
       if(head==null)
       return node;
  Node currentNode= head;
  while(currentNode.next!=null)
  {
      currentNode=currentNode.next;
      }

    currentNode.next=node;
    return head;
   }
 /**
  * Print All Elements of Linked List
  *
  * @param      Head of Linked List
  */
  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }


  }
}

Detect and Remove Loop in a Linked List

Detect & Remove Loop  From Linked List :
class DetectAndRemoveLoop
{
  static class Node {
   int data;
   Node next;
  }

  public static void main(String[] args) {
    Node node1 = new Node();
     node1.data = 1;
     Node node2 = new Node();
     node2.data = 2;
     Node node3 = new Node();
     node3.data = 3;
     Node node4 = new Node();
      node4.data = 4;
      Node node5 = new Node();
      node5.data = 5;
      Node node6 = new Node();
      node6.data = 6;
      Node node7 = new Node();
      node7.data = 7;
     node1.next = node2;
     node2.next = node3;
     node3.next = node4;
     node4.next=node5;
     node5.next=node6;
     node6.next=node7;
     node7.next=node3;
    if (detectAndRemove(node1) == true)
    {  printList(node1);  }
    else
    {System.out.println("No Loop Found"); }
  }
public  static boolean detectAndRemove(Node head)
  {
    Node slow=head;
    Node fast=head.next;
    while(fast!=null && fast.next!=null)
    {
      if(slow==fast)
      {
        break;
      }
    slow=slow.next;
    fast=fast.next.next;
  }
    if(slow==fast)
    {  slow=head;
        while(fast.next!=slow)
        {
          slow=slow.next;
          fast=fast.next;
        }
        fast.next=null;
        System.out.println("Loop Removed");
        return true;
    }

    return false;
  }

  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }
}
}