Monday, 4 April 2016

hackerrank:Sherlock and Squares

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)
    {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc=new Scanner(System.in);
        int test=sc.nextInt();
        while(test>0)
        {
           int a=sc.nextInt();
           int b=sc.nextInt();
           int count=(int)(Math.floor(Math.sqrt(b))-Math.ceil(Math.sqrt(a)))+1;
         
            System.out.println(count);
            test--;
        }
    }
}

hackerrank:Find Digits

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)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int test=sc.nextInt();
while(test>0)
{
int count=0;  
int n=sc.nextInt();
int arr[]=new int[12];
int i=0;
int temp=n;
while(n>0)
{
arr[i]=n%10;
n=n/10;
i++;
}
n=temp;
for(int k=0;k<i;k++)
{
if(arr[k]!=0)
{
if(n%arr[k]==0)
count++;
}
}
System.out.println(count);
test--;
}
}
}        

hackerrank:Sherlock and The Beast

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 t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++)
        {
            int n = in.nextInt();
            int div=n%3;
            if(n%3==0)
            {
            for(int i=0;i<n;i++)
                System.out.print("5");
                System.out.println();
            }
            else if(div==1&&n>=10)
            {
                for(int i=0;i<n-10;i++)
                    System.out.print("5");
                for(int i=0;i<10;i++)
                    System.out.print("3");
                System.out.println();
            }  
            else if(div==2&&n>=5)
            {
                for(int i=0;i<n-5;i++)
                    System.out.print("5");
                for(int i=0;i<5;i++)
                    System.out.print("3");  
            System.out.println();
            }
            else if(n%5==0)
            {
                for(int i=0;i<n;i++)
                    System.out.print("3");
                System.out.println();
            }
            else
                System.out.println("-1");

            }  
         
}
}

hackerrank:Angry Professor

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)
    {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc=new Scanner(System.in);
    int test=sc.nextInt();
    while(test>0)
    {
    int n=sc.nextInt();
    int k=sc.nextInt();
    int count1=0;  
        int arr[]=new int[n];
        for(int i=0;i<n;i++)
         {
            arr[i]=sc.nextInt();
            if(arr[i]<=0)
                count1++;
        }
        if(count1>=k)
            System.out.println("NO");
        else
            System.out.println("YES");
    }
}
}












Saturday, 20 February 2016

Producer-consumer problem

The producer-consumer problem is one of the most frequently encountered problems when we attempt multi threaded programming.First of all, let us see the characteristics of the producer-consumer problem:
  •     Producer produce items.
  •     Consumer consume the items produced by the producer.
  •     Producer finish production and let the consumers know that they are done.

package rakesh;

public class Producer_Consumer 
{
public static void main(String args[])
{
Methods m1=new Methods();
Producer p1=new Producer(m1,1);
Consumer c1=new Consumer(m1,1);
p1.start();
c1.start();
}

}
class Methods
{
private int content;
boolean available=false;
public  synchronized int get()
{
while(available==false)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
   }
available=false;
notifyAll();
return content;
}
public synchronized void put(int value)
{
while(available==true)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
   }
available=true;
content=value;
notifyAll();
}
}
class Producer extends Thread
{
Methods method;
int number;
Producer(Methods method,int num)
{
this.method=method;
number=num;
}
public void run()
{
for(int i=0;i<10;i++)
{
method.put(i);
System.out.println("Producer #"+this.number+":"+i);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}

class Consumer extends Thread
{
Methods method;
int number;
Consumer(Methods method,int num)
{
this.method=method;
number=num;
}
public void run()
{
for(int i=0;i<10;i++)
{
int value=method.get();
System.out.println("Consumer #"+this.number+":"+value);
}
}
}



Friday, 19 February 2016

Convert Berlin time to Digital time

package rakesh;

import java.util.Scanner;
public class Berlin
{
public static void main(String args[])
{
System.out.println("CONVERT BERLIN TIME TO DIGITAL TIME");
Scanner sc=new Scanner(System.in);
int red1[]=new int[4];
int red2[]=new int[4];
int yellowred[]=new int[11];
int yellowlight[]=new int[4];
System.out.println("Enter the array value in first array");
for(int i=0;i<red1.length;i++)
red1[i]=sc.nextInt();
System.out.println("Enter the array value in second array");
for(int i=0;i<red2.length;i++)
red2[i]=sc.nextInt();
System.out.println("Enter the array value in third array");
for(int i=0;i<yellowred.length;i++)
yellowred[i]=sc.nextInt();
System.out.println("Enter the array value in fourth array");
for(int i=0;i<yellowlight.length;i++)
yellowlight[i]=sc.nextInt();
int temp1=0;
int temp2=0;
for(int i=0;i<red1.length;i++)
{
if(red1[i]==1)
temp1=temp1+5*1;
}
for(int i=0;i<red2.length;i++)
{
if(red2[i]==1)
temp1=temp1+1*1;
}
String hours=temp1+"";
for(int i=0;i<yellowred.length;i++)
{
if(yellowred[i]==1)
temp2=temp2+5*1;
}
for(int i=0;i<yellowlight.length;i++)
{
if(yellowlight[i]==1)
temp2=temp2+1*1;
}
String minute=temp2+"";
System.out.println("Time is "+hours+":"+minute);
}
}


Convert Digital time to Berlin time

The Berlin clock is a clock that tells the time using a series of illuminated coloured blocks.
  • the top lamp blinks to show seconds-it is illuminated on even seconds and off on odd seconds.
  • The next two rows represent hours. The upper row represents 5 hour blocks and is made up of 4 red lamps. The lower row represents 1 hour blocks and is also made up of 4 red lamps.
  • The final two rows represent the minutes. The upper row represents 5 minute blocks, and is made up of 11 lamps- every third lamp is red, the rest are yellow. The bottom row represents 1 minute blocks, and is made up of 4 yellow lamps.

package rakesh;

import java.util.Scanner;

public class Digital
{
public static void main(String args[])
{
System.out.println("CONVERT DIGITAL TIME TO BERLIN TIME");
System.out.println("Enter time in hh:mm:ss Format");
Scanner sc=new Scanner(System.in);
sc.nextLine();
String Time=sc.nextLine();
String arr[]=Time.split(":");
int red1=Integer.parseInt(arr[0])/5;
int red2=Integer.parseInt(arr[0])%5;
int yellowred=Integer.parseInt(arr[1])/5;
int yellowlight=Integer.parseInt(arr[1])%5;
   if(Integer.parseInt(arr[2])%2==0)
    System.out.println("Y");
   else
    System.out.println("O");
for(int i=0;i<red1;i++)
System.out.print("R");
for(int i=0;i<(4-red1);i++)
System.out.print("O");
System.out.println();
for(int i=0;i<red2;i++)
System.out.print("R");
for(int i=0;i<(4-red2);i++)
System.out.print("O");
System.out.println();
for(int i=1;i<=yellowred;i++)
{
if(i%3==0)
System.out.print("R");
else
       System.out.print("Y");
}
for(int i=0;i<(11-yellowred);i++)
System.out.print("O");
System.out.println();
for(int i=0;i<yellowlight;i++)
System.out.print("Y");
for(int i=0;i<4-yellowlight;i++)
System.out.print("O");
}

}


Thursday, 18 February 2016

Print all permutations of a string

package rakesh;
import java.util.Scanner;
public class Permutations
{
static void swap(char array[],int a,int  b)
{
char temp=array[a];
array[a]=array[b];
array[b]=temp;
}

static void permutate(char array[],int start,int end)
{
if(start==end)
{
System.out.println();
for(int i=0;i<=end;i++)
System.out.print(array[i]);
}
else
{
for(int i=start;i<=end;i++)
{
swap(array,start,i);
permutate(array,start+1,end);
swap(array,start,i);
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
char array[]=input.toCharArray();
permutate(array,0,input.length()-1);
}
}

Wednesday, 10 February 2016

Displaying source code of a web page

//URLConnectionExample.java

import java.io.*;
import java.net.*;
public class URLConnectionExample
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://javaforocpjp.blogspot.in/index.html");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}  

downlaod file from Server

//MyServer.java

import java.io.*;
import java.util.*;
import java.net.*;
class MyServer
{
public static void main(String args[])
{
try
{
ServerSocket s1=new ServerSocket(2233);
Socket s=s1.accept();
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
FileInputStream file=new FileInputStream("input.txt");
String msg="";
char ch=0;
int i=0;
while((i=file.read())!=-1)
{
char c=(char)i;
msg+=c;
}
dout.writeUTF(msg);
dout.flush();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

//MyClient.java

import java.io.*;
import java.util.*;
import java.net.*;
class MyClient
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",2233);
DataInputStream dis=new DataInputStream(s.getInputStream());
FileOutputStream file=new FileOutputStream("output.txt");
String msg=(String)dis.readUTF();
byte brr[]=msg.getBytes();
file.write(brr);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Chat Application in Java

//MyServer.java
import java.net.*;
import java.io.*;
import java.util.*;
class MyServer
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
Scanner sc=new Scanner(System.in);
String str="",msg="";
while(!str.equals("stop"))
{
str=(String)dis.readUTF();
System.out.println("Client :"+str);
System.out.print("Server :");
msg=sc.nextLine();
dout.writeUTF(msg);
dout.flush();
}
dis.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//MyClient.java
import java.net.*;
import java.io.*;
import java.util.*;
class MyClient
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",3333);
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
Scanner sc=new Scanner(System.in);
String str="",msg="";
while(!str.equals("stop"))
{
System.out.print("Client :");
msg=sc.nextLine();
dout.writeUTF(msg);
dout.flush();
str=(String)dis.readUTF();
System.out.println("Server :"+str);
}
dis.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}


Sunday, 22 November 2015

Skilrock Technologies Interview Questions

1.Write a Program to find the frequency of a number in a two-dimesnsional array?

 import java.util.Scanner;  
 class FindFrequency {  
   public static void main(String args[]) {  
     Scanner sc = new Scanner(System.in);  
     int value[] = {  
       0, 1, 2, 3, 4, 5, 6, 7, 8, 9  
     };  
     int flag[] = new int[10];  
     System.out.println("Enter the value of n:");  
     int n = sc.nextInt();  
     int arr[][] = new int[n][n];  
     for (int i = 0; i < n; i++) {  
       for (int j = 0; j < n; j++) {  
         arr[i][j] = sc.nextInt();  
       }  
     }  
     for (int i = 0; i < n; i++) {  
       for (int j = 0; j < n; j++) {  
         Inner: for (int k = 0; k < 10; k++) {  
           if (arr[i][j] == value[k]) {  
             flag[k]++;  
             break Inner;  
           }  
         }  
       }  
     }  
     for (int k = 0; k < 10; k++)  
       System.out.println("value of" + k + "is" + flag[k]);  
   }  
 }  







2.Write a Program to find the sum of diagonal elements using one variable?

 import java.util.Scanner;  
 class Sum {  
   public static void main(String args[]) {  
     Scanner sc = new Scanner(System.in);  
     int n = sc.nextInt();  
     int arr[][] = new int[n][n];  
     for (int i = 0; i < n; i++) {  
       for (int j = 0; j < n; j++) {  
         arr[i][j] = sc.nextInt();  
       }  
     }  
     int sum = 0;  
     for (int i = 0; i < n; i++) {  
       sum = sum + arr[i][i];  
     }  
     System.out.println(sum);  
   }  
 }  

3.Tell me about your project?
   This Question is asked in each Technical Interview.Prepare these question self:-
    A.Disadvantage of old System.
    B.Advantage of new System.
    C.Requirement Specification.
    D.Process implemented in project
    E.Tables Used(Database).

4.Other Questions:-
   A:-Sudoku
   B:-bugs in any Real world applications like Facebook/Whatsapp
   C:-Second Highest salary (SQL Query)
   D:-Merging of Two binary Search tree
   E:-Manipulation of Strings(like remove kth character from a String)
 
All The Best Guys!
Keep Calm & NeverGiveUp

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
   

Wednesday, 11 November 2015

Create your Own appletviewer

//Test.java
import java.applet.Applet;
import java.awt.Graphics;
class Test extends Applet
{
public void paint(Graphics g)
{
g.drawString("rakesh",200,200);
}
}

//MyViewer.java

import java.awt.Frame;
import java.awt.Graphics;
import java.applet.Applet;
class MyViewer extends Frame
{
public static void main(String args[]) throws Exception
{
MyViewer v1=new MyViewer();
v1.setSize(400,400);
v1.setLayout(null);
v1.setVisible(true);
Class c=Class.forName(args[0]);
Applet a1=(Applet)c.newInstance();
a1.start();
Graphics g=v1.getGraphics();
a1.paint(g);
a1.stop();
}
}



Write a Program that works as javap tool

 import java.lang.reflect.*;  
 class JavaP {  
      public static void main(String args[]) {  
           try {  
                Class c = Class.forName(args[0]);  
                System.out.println("Fields.........................................");  
                Field f[] = c.getDeclaredFields();  
                for (int i = 0; i < f.length; i++)  
                     System.out.println(f[i]);  
                System.out.println("Constructors...................................");  
                Constructor t[] = c.getDeclaredConstructors();  
                for (int i = 0; i < t.length; i++)  
                     System.out.println(t[i]);  
                System.out.println("Methods........................................");  
                Method m[] = c.getDeclaredMethods();  
                for (int i = 0; i < m.length; i++)  
                     System.out.println(m[i]);  
           } catch (ClassNotFoundException e) {  
                System.out.println(e.getMessage());  
           } catch (SecurityException e) {  
                System.out.println(e.getMessage());  
           }  
      }  
 }  

Monday, 9 November 2015

Quick review of Collections

The Most Commonly used Core interfaces are:-

1.Collection 
2. Set 
3. SortedSet 
4. List 
5. Map 
6. SortedMap 
7. Queue

and the most frequently used core concrete implementation classes are

1. HashMap 
2. HashSet 
3. ArrayList 
4. PriorityQueue 
5. Collections 
6. Hashtable 
7. LinkedHashSet 
8. Vector 
9. Arrays 
10. TreeMap 
11. TreeSet 
12. LinkedList 
13. LinkedHashMap 


Remember none of the Map-related classes and interfaces extend from Collection.

So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all thought of as collections, none are actually extended from Collection(interface).

collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.

Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement. There are no direct implementations of Collection.)

Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.

Collections come in four basic flavors:

1. Lists of things Ordered, duplicates allowed, with an index.

2. Sets of things May or may not be ordered and/or sorted; duplicates not allowed.

3. Maps of things with keys May or may not be ordered and/or sorted; duplicate keys are not allowed.

4. Queues of things to process Ordered by FIFO or by priority.


But there are sub-flavors within those four flavors of collections:

Sorted 
Unsorted
Ordered
Unordered

An implementation class can be unsorted and unordered, ordered but unsorted, or both ordered and sorted. 

But an implementation can never be sorted but unordered, because sorting is a specific type of ordering. 
For example, a HashSet is an unordered, unsorted set, while a LinkedHashSet is an ordered (but not sorted) set that maintains the order in which objects were inserted.

Ordered: When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order. 

Sorted: Order in the collection is determined according to some rule or rules, known as the sort order. A sort order has nothing to do with when an object was added to the collection, or when was the last time it was accessed, or what "position" it was added at. Sorting is done based on properties of the objects themselves. You put objects into the collection, and the collection will figure out what order to put them in, based on the sort order. 

A collection that keeps an order (such as any List, which uses insertion order) is not really considered sorted unless it sorts using some kind of sort order. 

Most commonly, the sort order used is something called the natural order.

List Interface:

A List cares about the index. (Ordered but Not Sorted)

The one thing that List has that non-lists don't have is a set of methods related to the index. 

All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. 

ArrayList: Fast iteration and fast random access.

ArrayList implements RandomAccess interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant time) random access." 

Vector: It's like a slower ArrayList, but it has synchronized methods.

LinkedList: Elements are doubly-linked to one another. Good for adding/remove elements to the ends, i.e., stacks and queues.


Note : 
--> Choose ArrayList over a LinkedList when you need fast iteration i.e random access.
--> Go for Linked List when you need fast insertion and deletion.


Set Interface : A Set cares about uniqueness—it doesn't allow duplicates. 

HashSet: Fast access, assures no duplicates, provides no ordering.

LinkedHashSet: No duplicates; iterates by insertion order.

TreeSet: No duplicates; iterates in sorted order. Implements SortedSet.

Note : When using HashSet or LinkedHashSet, the objects you add to them must override hashCode(). If they don't override hashcode(), the default object. hashcode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Map Interface : Cares about unique identifiers. Supports use of key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. 

Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

HashMap: unsorted, unordered Map. Fastest updates (key/value pairs); allows one null key, many null values.

Hashtable : Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.

LinkedHashMap : Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.

TreeMap : A sorted map. Implements SortedMap.

Note: 
LinkedList ---> faster insertions and deletions and slower iterations (compared to arraylist)
LinkedHashMap ---> faster iterations and slower insertions and deletions (compared to HashMap)

Queue Interface : Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

PriorityQueue: A to-do list ordered by the element's priority.

Saturday, 31 October 2015

Basic Interview Questions

Multiplication of two matrixes


import java.util.Scanner;
class Multiplication
{
void doMultiply(int arr1[][],int arr2[][])
{
int arr3[][]=new int[3][3];
for(int i=0;i<arr1.length;i++)
{
for(int j=0;j<arr2[0].length;j++)
{
arr3[i][j]=0;
for(int k=0;k<arr1[0].length;k++)
{
arr3[i][j]=arr3[i][j]+arr1[i][k]*arr2[k][j];
}
}
}
for(int i=0;i<arr3.length;i++)
{
for(int j=0;j<arr3[i].length;j++)
{
System.out.print(arr3[i][j]+"\t");
}
System.out.println();
}
}
}
class MultiplicationTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int arr1[][]=new int[3][3];
int arr2[][]=new int[3][3];
System.out.println("Enter the elements of first matrix:");
for(int i=0;i<arr1.length;i++)
{
for(int j=0;j<arr1[i].length;j++)
{
arr1[i][j]=sc.nextInt();
}
}
System.out.println("Enter the elements of second matrix:");
for(int i=0;i<arr2.length;i++)
{
for(int j=0;j<arr2[i].length;j++)
{
arr2[i][j]=sc.nextInt();
}
}
Multiplication m1=new Multiplication();
m1.doMultiply(arr1,arr2);
}
}

Merging two sorted arrays


import java.util.Scanner;
class Merge
{
void toMerge(int arr1[],int arr2[])
{
int arr3[]=new int[arr1.length+arr2.length];
int i=0,j=0,k=0;
while(i<arr1.length&&j<arr2.length)
{
if(arr1[i]<arr2[j])
{
arr3[k]=arr1[i];
k++;
i++;
}
else
{
arr3[k]=arr2[j];
k++;
j++;
}
}
for(int m=j;m<arr2.length;m++,k++)
arr3[k]=arr2[m];
for(int m=i;m<arr1.length;m++,k++)
arr3[k]=arr1[m];
for(int t=0;t<k;t++)
System.out.print(arr3[t]+"\t");
}
}
class MergeTest
{
public static void main(String args[])
{
Merge m1=new Merge();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of n:");
int n=sc.nextInt();
System.out.println("Enter the value of m:");
int m=sc.nextInt();
int arr1[]=new int[n];
int arr2[]=new int[m];
System.out.println("Enter the elements of first array in sorted order:");
for(int i=0;i<n;i++)
arr1[i]=sc.nextInt();
System.out.println("Enter the elements of second array in sorted order:");
for(int i=0;i<m;i++)
arr2[i]=sc.nextInt();
m1.toMerge(arr1,arr2);
}
}