Thursday, 22 February 2018

Check for balanced parentheses in an expression using Stack class of Java

import java.util.*;
class Solution{
 
   public static void main(String []argh)
   {
      Scanner sc = new Scanner(System.in);
      Stack<Character> stack = new Stack<>();
      while (sc.hasNext()) {
         String input=sc.next();
          for(int i=0;i<input.length();i++)
          {
              char c=input.charAt(i);
           
              if(c=='(' || c=='{' || c=='[')
                 stack.push(c);
             
             
              else if(!(stack.isEmpty())){
                    if((c==')' && stack.peek()=='(' )|| (c=='}' && stack.peek()=='{') || c==']' && stack.peek()=='[')
                        stack.pop();
                 
              }
              else stack.push(c);
             
          }
         
          if(stack.empty())
              System.out.println("true");
          else
              System.out.println("false");
          stack.clear();// IMPORTANT :)
      }
     
   
   }
}

Wednesday, 21 February 2018

Two Dimensional Dynamic Array in Java

/*Coded By-Shivam Tripathi*/
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 sc=new Scanner(System.in);
        List<ArrayList<Integer>> ar=new ArrayList<ArrayList<Integer>>();
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            ar.add(new ArrayList<Integer>());
        }
        for(int i=0;i<n;i++)
        {
            int d=sc.nextInt();
            for(int j=0;j<d;j++)
            {
                int num=sc.nextInt();
                ar.get(i).add(num);
            }
        }
         int q = sc.nextInt();
        for(int i=0; i<q; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
           
            try {
                System.out.println(ar.get(x-1).get(y-1));
            } catch(Exception e) {
                System.out.println("ERROR!");
            }
        }
       
       
    }
}

Wednesday, 14 February 2018

Finding Square Root of a number without using in-built function

Using Binary Search
float sqrt(n) {
    low = 0.0;
    high = (float)n+1;
    while ((high-low) > 0.00001) {
        mid = (low+high) / 2;
        if (mid*mid < n) {
            low = mid;
        }
        else {
            high = mid;
        }
    }
    return low;
}

Wednesday, 24 January 2018

GCD and LCM of n numbers stored in an array.

#include<stdio.h>
#include<stdlib.h>
int gcd(int a,int b)
{
if(a==0)
return b;
else
return gcd(b%a,a);
}
int lcm(int a,int b)
{
return a*(b/gcd(a,b));
}
int main()
{
int i,n;
/*To calculate GCD of n elementst we have to initailize starting variable with 0 (no with 1 )*/
int resgcd=0;
/*To calculate GCD of n elementst we have to initailize starting variable with 1 (no with 0 )*/
int reslcm=1;
printf("Enter the size of array:");
scanf("%d",&n);
int *ar=(int *)malloc(n*sizeof(int));
printf("\nEnter the elements of array:\n");
for(i=0;i<n;i++)
scanf("%d",&ar[i]);
for(i=0;i<n;i++)
resgcd=gcd(resgcd,ar[i]);
for(i=0;i<n;i++)
reslcm=lcm(reslcm,ar[i]);
printf("GCD : %d",resgcd);
printf("\nLCM : %d",reslcm);
return 0;
}

Monday, 22 January 2018

Implementing Graph by Adjacency List using Java

import java.util.LinkedlIst;
class Graph
{
    int v;
    LinkedList<Integer> a[];
    Graph(int v)
    {
     
        this.v=v;
        a=new LinkedList[5];
        for(int i=0;i<v;i++)
        {
            a[i]=new LinkedList<>();
        }
       
    }
    void addEdge(int source,int destination)
    {
        a[source].add(destination);
        a[destination].add(source);
    }
    void printGraph(Graph graph)
    {     
        for(int i = 0; i < v; i++)
        {
            System.out.println("Adjacency list of vertex "+ i);
            System.out.print("head");
            for(Integer j: graph.a[i]){
                System.out.print(" -> "+j);
            }
            System.out.println("\n");
        }
    }
   
}
class demo{
    public static void main(String args[])
    {
        // create the graph given in above figure
        int V = 5;
        Graph graph = new Graph(V);
        graph.addEdge(0,1);
        graph.addEdge(0,4);
        graph.addEdge(1,2);
        graph.addEdge(1,3);
        graph.addEdge(1,4);
        graph.addEdge(2,3);
        graph.addEdge(3,4);
     
        // print the adjacency list representation of
        // the above graph
        graph.printGraph(graph);
    }
}

Friday, 19 January 2018

Queue using Two Stacks

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

struct stack
{
    int data;
    struct stack *next;
};
struct stack* push(struct stack *head,int num)
{

    struct stack* temp=(struct stack*)malloc(sizeof(struct stack));
    temp->data=num;
    temp->next=NULL;
    if(head==NULL)
    {
    head=temp;
}

else
{
temp->next=head;
head=temp;
}
return head;
}
int pop(struct stack **head)
{
int temp=(*head)->data;
*head=(*head)->next;
return temp;

}

int main()
{
    int choice,temp,q,num,i,a;
    struct stack* stack_ins=NULL;
    struct stack* stack_del=NULL;
    scanf("%d",& q);
    for(i=0;i<q;i++)
    {
        scanf("%d",&choice);
        if(choice==1)
        {
            scanf("%d",&num);
            stack_ins=push(stack_ins,num);
        }
        if(choice==2)
        {
            if(stack_del==NULL)
            {
              while(stack_ins!=NULL)
              {
                  temp=pop(&stack_ins);
                  stack_del=push(stack_del,temp);
              }
            }
            a=pop(&stack_del);
        }
        if(choice==3)
        {
          if(stack_del==NULL)
            {
              while(stack_ins!=NULL)
              {
                  temp=pop(&stack_ins);
                  stack_del=push(stack_del,temp);
              }
            }
            printf("%d\n",stack_del->data); 
        }
    }
 
       
    return 0;
}

Thursday, 18 January 2018

C Program to find pair whose sum is closest to zero.

#include<stdio.h>
#include<stdlib.h>

#define MAX 100
/*Assuming that array is sorted in ascending order*/
int main(){

int sum,i,j,n=10,p,q;
int *arr=(int *)malloc(MAX*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

int tmp;
j=n-1;i=0;
sum=99999;
while(j>i){

tmp=arr[i]+arr[j];
if(abs(sum)>abs(tmp))
{
sum=arr[i]+arr[j];
p=i;q=j;

}
else if(tmp<0)
{
i++;
}
else j--;
}

printf("\nThe pair which has sum closest to zero: %d and %d",arr[p],arr[q]);
return 0;
}