Tuesday 6 March 2018

TreeMap with combo of Integer and StringBuilder in Java

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();
        TreeMap<Integer,StringBuilder> tm=new TreeMap<>();
       for(int m=0;m<100;m++){
StringBuilder sb = new StringBuilder("");
tm.put(m,sb);
}
        for(int a0 = 0; a0 < n; a0++){
            int x = in.nextInt();
            String s = in.next();
           
            if(a0<(n/2))
            {
                StringBuilder sold=tm.get(x);
                sold.append("- ");
                tm.put(x,sold);
            }
            else
            {
               
                StringBuilder sold=tm.get(x);
                sold.append(s+" ");
                tm.put(x,sold);
            }
           
        }
     
        for (Map.Entry<Integer, StringBuilder> entry : tm.entrySet()) {
         StringBuilder s=entry.getValue();
            //for(int i=0;i<s.length();i++)
               
            System.out.print(s);
        }
        in.close();
    }
}

Thursday 1 March 2018

Java 2D ArrayList-Linear Search

import java.util.*;
public class demo
{
    static int search(ArrayList<Integer>a,int num)
    {
        for(int i=0;i<a.size();i++)
        {
            if(a.get(i)==num)
                return i;
        }
        return -1;
    }
    public static void main(String args[])
    {
        int k=0;
        ArrayList<ArrayList<Integer>> a=new ArrayList<>();
       
        //I always forget to do this.;)
        for(int i=0;i<5;i++)
        {
            a.add(new ArrayList<>());
        }
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<4;j++)
            {
                k++;
            a.get(i).add(k);   
            }
        }
        int s=search(a.get(1),8);
        System.out.println(a);
        System.out.println(s);
       
    }
}

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

Predefined Quick Sort Implementation in C

#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a,const void *b){
return(*(char *)b-*(char *)a);

}

int main()
{
int i;
char arr[10];
printf("Enter elements:");
for(i=0;i<10;i++)
{
scanf("%c",&arr[i]);
}
qsort(arr,10,sizeof(char),cmp);
fputs(arr,stdout);
return 0;
}

C Program to check whether a string is Pangram

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main(){
int flag,i,n;
flag=0;i=0;
char str[100],modstr[100];
int ar[256]={0};
printf("Enter the string:\n");
fgets(str,100,stdin);


while(str[i]){
modstr[i]=toupper(str[i]);
i++;
}
i=0;
while(modstr[i]){
ar[modstr[i]]=1;
i++;
}

for(i='A';i<='Z';i++){
if(ar[i]==0){
flag=1;
break;
}
}


if(flag==1){
printf("\nNot a Panagram");
}
else
printf("\nString is a Panagram");
return 0;
}

C Program to understand some basic operations on linked list

#include<stdio.h>
#include<stdlib.h>
struct linkedlist
{
int data;
struct linkedlist *next;
};


int length(struct linkedlist *head){
int count=0;
struct linkedlist *head1=head;
while(head1)
{
count++;
head1=head1->next;
}
return count;

}

struct linkedlist* insert(struct linkedlist *head,int num,int pos)
{
struct linkedlist *node,*head1;

int i;
node=(struct linkedlist*)malloc(sizeof(struct linkedlist));

node->data=num;
node->next=NULL;
head1=head;
if(head==NULL && pos==1)
{
head=node;
printf("Element Inserted Successfully.\n");
}
else if(pos<length(head)+1){
if(pos==1){
node->next=head;
head=node;
}else{
for(head1=head,i=1;i<pos-1 && head1;i++,head1=head1->next);
node->next=head1->next;
head1->next=node;
}}
else if(pos>1 && pos<=length(head)+1)
{
for(head1=head,i=1;i<pos-1 && head1;i++,head1=head1->next);

head1->next=node;

printf("\nElement Inserted Successfully\n");
}

else printf("Error in Insertion\n");

return head;

}
void showlist(struct linkedlist *head){
struct linkedlist *head2=head;
if(head2==NULL)printf("\nLinked List is empty.");
else{
while(head2)
{
printf("  %d   ",head2->data);
head2=head2->next;
}
}

}

void reverse(struct linkedlist **head)
{
struct linkedlist *temp=NULL,*prev=NULL,*head1=*head;
//while(head1){prev=head1;head1=head1->next;new_head=head1;}
while(head1)
{
temp=head1->next;
head1->next=prev;
prev=head1;
head1=temp;

}*head=prev;
}
struct linkedlist* clone_list(struct linkedlist *head)
{

struct linkedlist *prev=NULL,*clonedLL=NULL,*clonedLLhead=NULL;
struct linkedlist *head1=head;
while(head1){
clonedLL=(struct linkedlist*)malloc(sizeof(struct linkedlist));
clonedLL->data=head1->data;
clonedLL->next=NULL;

showlist(head1);


clonedLLhead=clonedLL;
prev->next=clonedLL;
prev=clonedLL;
head1=head1->next;

}
return clonedLLhead;
}

int main()
{

struct linkedlist *cloneh=NULL,*head=NULL;

int i,num,pos,posdel;
do{
printf("Choose any operation:\n1.Insert an element.\n2.Delete an element \n3.View the Linked list.\n4.Reverse the lsit.\n5.Clone the list\n6.Exit\n");
scanf("%d",&i);
if(i==1)
{
printf("\nEnter the element to insert:");
scanf("%d",&num);
printf("Enter  a valid position:");
scanf("%d",&pos);
head=insert(head,num,pos);
}

if(i==2)
{
printf("\nEnter the position to delete:");
scanf("%d",&posdel);
//delete(head,posdel);
}
if(i==3)
{
showlist(head);
}
if(i==4)
{
reverse(&head);
}
if(i==5)
{
cloneh=clone_list(head);
printf("\nCloned Linked List:\n");
showlist(cloneh);
}
if(i==6)
break;
}while(1);
//free(head);
return 0;
}

C program to sort numbers using Insertion Sort

#include<stdio.h>
#include<stdlib.h>
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;

}
void insertionSort(int *ar,int size)
{
int i,k,j,temp;
for(i=0;i<size;i++)
{
temp=ar[i];
j=i-1;
while(ar[j]>ar[i] && j>=0)
{

swap(&ar[j],&ar[i]);
i=j;
j--;

}

}
}

void printArray(int *arr,int size){
int i;

for(i=0;i<size;i++)
printf("%d\t",arr[i]);


}

int main(){

int i,size,*arr;
arr=(int *)malloc(size*sizeof(int));
printf("\nEnter the size of array:");
scanf("%d",&size);
printf("\nEnter the elements of array:");
for(i=0;i<size;i++){
scanf("%d",&arr[i]);
}
printArray(arr,size);
insertionSort(arr,size);
printArray(arr,size);
return 0;
}

C Program to sort the numbers using Heap Sort

#include<stdio.h>
#include<stdlib.h>
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
void heapify(int *ar,int i,int size)
{
int largest=i;
int l=2*i;
int r=2*i+1;
if(l<size && ar[l]>ar[largest])
largest=l;
if(r<size && ar[r]>ar[largest])
largest=r;
if(largest!=i)
{swap(&ar[i],&ar[largest]);heapify(ar,largest,size);}
}
void heapSort(int *ar,int size){
int i;
for(i=(size/2)-1;i>=0;i--)
heapify(ar,i,size);
for(i=size-1;i>=0;i--)
{
swap(&ar[0],&ar[i]);

heapify(ar,0,i);
}
}
void printArray(int *ar,int size)
{
int i;
for(i=0;i<size;i++)
{
printf("%d\t",ar[i]);
}
printf("\n");
}

int main()
{
int i,n;
printf("Enter the size of array:");
scanf("%d",&n);
int *ar=(int *)malloc(n*sizeof(int));
printf("\nEnter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",&ar[i]);
printArray(ar,n);
heapSort(ar,n);
printArray(ar,n);
return 0;
}

C Program to find first repeating character in a string

#include<stdio.h>
#include<string.h>
char FirstRepeatedChar(char *str){
int i;
int len=strlen(str)-1;
int count[256];
for(i=0;i<256;i++)
count[i]=0;

for(i=0;i<len;i++)
{
if(count[str[i]]==1){

printf("%c",str[i]);
break;
}
else count[str[i]]++;
}
if(i==len)
printf("\nNo characters found");
return 0;
}

int main()
{
char str[100];
int len;
char c;
printf("ENter string:");
fgets(str,100,stdin);
len=strlen(str)-1;
c=FirstRepeatedChar(str);


return 0;

}

C Program to reverse a string.

#include<stdio.h>
#include<string.h>
void rev(char str[],int start,int end)
{
char tmp;
if(start<=end)
{
tmp=str[start];
str[start]=str[end];
str[end]=tmp;
rev(str,start+1,end-1);
}

}

int main()
{
char str[100];
printf("Enter the string:\n");
fgets(str,100,stdin);
int n;
n=strlen(str);
rev(str,0,n-1);
fputs(str,stdout);

return 0;
}

C Program to Sort Numbers using Bubble Sort

#include<stdio.h>
#include<stdlib.h>
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;

}
void bubbleSort(int *arr,int size)
{
int i,j,swapped;
for(i=0;i<size-1;i++)
{ swapped=0;
for(j=0;j<size-i-1;j++)
{
if(arr[j]>arr[j+1])
{
swap(&arr[j],&arr[j+1]);
swapped=1;
}

}
if(!swapped)break;
}
}

void printArray(int *arr,int size){
int i;
printf("\nArray is :");
for(i=0;i<size;i++)
printf("%d\t",arr[i]);


}

int main(){

int i,size,*arr;
arr=(int *)malloc(size*sizeof(int));
printf("\nEnter the size of array:");
scanf("%d",&size);
printf("\nEnter the elements of array:");
for(i=0;i<size;i++){
scanf("%d",&arr[i]);
}
printArray(arr,size);
bubbleSort(arr,size);
printArray(arr,size);
return 0;
}

C Program to search numbers using Binary Search.

/*Binary Serach for sorted array
By-Shivam Tripathi
*/
#include<stdio.h>
#include<stdlib.h>
/*The elements of array should be sorted in Ascending order.*/

int binSearch(int *ar,int start,int end,int num)
{
if(end>=start){

int mid=(start+end)/2;
if(ar[mid]==num)
return (mid+1);
else if(ar[mid]<num)
return binSearch(ar,mid+1,end,num);
else
return binSearch(ar,start,mid-1,num);
}
return -1;
}
int main()
{
int n,i,pos,num;
printf("\nEnter the size of array:");
scanf("%d",&n);
printf("\nEnter element to search:");
scanf("%d",&num);
int *ar=(int *)malloc(n*sizeof(int));
printf("\nEnter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",ar+i);
}

pos=binSearch(ar,0,n-1,num);
if(num>0)
printf("Location of element in array:%d",pos);
return 0;
}