Monday, December 28, 2015

Factorial Using Recursion In Java

Factorials are very simple things. They're just products, indicated by an exclamation mark. For instance, "four factorial" is written as "4!" and means 1×2×3×4 = 24. In general, n! ("enn factorial") means the product of all the whole numbers from 1 to n; that is, n! = 1×2×3×...×n.

The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion
public static int factorial(int N) { 
   if (N == 1) return 1; 
else
   return N * factorial(N-1); 
} 


public class FactorialRecursion {

public static void main(String[] args) {

int n=5;
System.out.println(fact(n));


}
public static int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);

}

}

Thursday, December 3, 2015

Custome Sorting Of Array Without Using Sort Method

Sorting of an array without using sort method in java is most popular in interview. so here is the solution. 
first i am taking an int type array a now for each loop is to printing the array
(you can skip this loop its not important.). 
now take an int temp which will store the value for temprary. 
now for loop wil be start from index 0 to length-1 inside this for loop another
loop will be start from 0 to length of array-2 . 
now in the if condition it will check if (a[j]<a[j+1] ) if this condition will be true than 
in temp value of a[j] will be store and a[j] will store value ofa[j+1].
in this step no. will swap according to value .

public class CustomSorting {

public static void main(String[] args) {

int [] a={7,45,36,64,77,34,72,95};
for(int no:a)
{
System.out.println("before sorting  "+no);
}

//temp store value temprary

int temp;
for(int i=0; i<=a.length-1;i++)
{
for( int j=0; j<=a.length-2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("  ..........   ");
for(int no:a)
  {
           System.out.println(" after sorting  "+no);
   }
}
}

}

Thursday, September 10, 2015

Convert Decimal To Binary



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class DecimalToBinary {

public static void main(String[] args) {

Scanner scn=new Scanner(System.in);
System.out.println(" type a no. to convert into binary");
int n=scn.nextInt();
binary(n);
}

public static void binary(int n)
{
List<Integer> ls=new ArrayList();
while(n>0)
{
if(n%2==0)
{
n=n/2;
ls.add(0);
}
else if (n%2==1)
{
n=n/2;
ls.add(1);
}
else
{
ls.add(1);
}
}
Collections.reverse(ls);
System.out.println(ls);
}
}

Tuesday, July 14, 2015

Singleton in java

  1. Java Singleton Class Example Using Private Constructor. We can make constructor as private. So that We can not create an object outside of the class. This property is useful to create singleton class injavaSingleton pattern helps us to keep only one instance of a class at any time.


class Demo1
{
private Demo1()
{
System.out.println(" from demo 1 ");
}
static  Demo1 a=new Demo1();
 
public static Demo1 getInstance()
{
return a;
}

}

public class SingletonExampl 
     {
public static void main(String[] args) 
        {
Demo1 b=Demo1.getInstance();
}

}

Friday, July 10, 2015

Lonely Integer

Problem Statement
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
Input Format
The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.
Output Format
Output S, the number that occurs only once.
Sample Input:1
1
1
Sample Output:1
1
Sample Input:2
3
1 1 2
Sample Output:2
2
Sample Input:3
5
0 0 1 2 1
Sample Output:3
2
Explanation
In the first input, we see only one element (1) and that element is the answer.
In the second input, we see three elements; 1 occurs at two places and 2 only once. Thus, the answer is 2.
In the third input, we see five elements. 1 and 0 occur twice. The element that occurs only once is 2.


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

public class Solution {
static int lonelyinteger(int[] a) {
 
    int result=0;
    for(int i=0;i<=a.length-1;i++)
        {
        result=result^a[i];
    }
return result;

    }
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;
     
        int _a_size = Integer.parseInt(in.nextLine());
        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");
     
        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }
     
        res = lonelyinteger(_a);
        System.out.println(res);
     
    }
}

Genrate Random Numbers In java

An instance of Random class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula.

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.


Many applications will find the method Math.random() simpler to use.



import java.util.*;

public class GenrateRandomNumber {

public static void main(String[] args) {

Random rand = new Random(System.currentTimeMillis());
int number ;
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=0; i<10;i++){
number=rand.nextInt(101);
al.add(number);

}
display(al);
}

static void display(ArrayList arr)
{
for(int i=0; i<arr.size(); i++)
System.out.print(arr.get(i)+" ");

}

}

Even Odd Program in Java

  1. An even number is an integer which is "evenly divisible" by two. This means that if the integer is divided by 2, it yields no remainder. Zero is an even number because zero divided by two equals zero. Even numbers can be either positive or negative.
  2. An odd number is an integer of the form , where is an integer. The odd numbers are therefore ..., , , 1, 3, 5, 7, .... Integers which are not odd are called even. Odd numbers leave a remainder of 1 when divided by two, i.e., the congruence holds for odd .
  3. In this program first if condition will check if no. Is greater than 0 or not if yes than no. Will go inside the loop for operation if not than it will return to starting point. 
  4. Inside the loop if no. Will devide by 2 and remainder will be 0 than no. Is even . and if remainder will be 1 than no. Is odd.

import java.util.Scanner;

public class EvenOdd {


public static void main(String[] args)
{

Scanner scn=new Scanner (System.in);
System.out.println(" Type a no. to chech even or odd");
int n=scn.nextInt();
if(n>0)
{
if(n%2==0)
{
System.out.println("No. Is Even");
}
else
{
System.out.println("No.Is Odd");
}
}
else
{
System.out.println("Plese type a valid no. exepting 0");
}

}

}

Thursday, July 9, 2015

Simple Threading Program in java Using Runnable Interface

public class InterfaceExample implements  Runnable {

public void run()
{

System.out.println(" run method running");

}
public void first()
{
for(int i=0;i<=5;i++)
{
try{
Thread.sleep(100);
System.out.println(i);
}
catch(Exception e)
{

}
}
}
public void second()
{
for(int i=6;i<=10;i++)
{
try{
Thread.sleep(500);
System.out.println(i);
}
catch(Exception e)
{

}
}
}


public static void main(String[] args)  {

InterfaceExample ie =new InterfaceExample();
Thread td=new Thread(ie);
td.start();
ie.first();
ie.second();
}

}

Consumer Producer Program In Threading

Consumer Producer program is most popular program in threading. here is the solution of the program. UpdateThread class updating the new stock And ConsumeThread class will get the items from the updated stock. if consumer requerd more than the stock so consumer has to wait untill the update thread class will update the new stock. after updating new stock consumer will get the required stock .




class Stock
{
int stock;
synchronized void update(int n)
{
System.out.println(" updates starts");
stock+=n;
System.out.println(" stock update to "+stock);
notify();
}
synchronized void consume(int n)
{
System.out.println(" consume need  : "+n);
while(n>=stock)
{
System.out.println("stock issue wait for update .....");
try
                    {
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(" exception found !!!!");
}
try
                     {
wait();
}
catch(Exception e)
{
System.out.println(" Exception occurd !!!!!!");
}
}
stock-=n;
System.out.println(" consumer used :"+n);

}
}

class UpdatedThread implements Runnable
{
Stock s;
int n;
UpdatedThread(Stock s, int n)
{
this.s=s;
this.n=n;
new Thread(this).start();
  }
public void run()
{
s.update(n);
}

 }
class ConsumeThread implements Runnable
{
Stock s;
int n;
ConsumeThread(Stock s, int n)
{
this.s=s;
this.n=n;
new Thread(this).start();

}
public void run()
{
s.consume(n);
}
}

public class DeadlockConsumerProducer
{

public static void main(String[] args)
          {

Stock s=new Stock();

               // consumer required 18 items those are not in producers stock

new ConsumeThread(s,18);

               // producer update the stock after this consumer will get 18 items

new UpdatedThread(s,20);

}

}

Monday, July 6, 2015

The best Internet Browser

In the race for the best Internet browser, there's now a new contender for it, this browser is called the: "The Semantic Mind-Reader!" After its promo on the world wide web, everyone's been desperately waiting for the browser to be released. And why shouldn't they be curious about it, after all, it's the new project of our very own genius "Little Jhool!" He's worked very hard for this browser, and to add new mind reading features to it.
Apart from the various security powers it possesses, it's called the mind-reader for a reason. Here's why:
  • You don't need to type 'www.' to open a website anymore.
  • Though, you still need to type '.com' to open a website.
  • The browser predicts ALL THE VOWELS in the name of the website. (Not '.com', though. Again!)
  • Obviously, this means you can type the name of a website faster and save some time.

Input format:
The first line contains tc, the number of test cases.
The second line contains the name of websites, as a string.
Output format:
You have to print the ratio of characters you would have typed in Jhool's browser, to your normal browser.
Constraints:
1 <= tc <= 100
1 <= Length of the website <= 200
NOTE: You do NOT need to print the output in its lowest format. You should print in its original fraction format.
The names of all the websites will be in small case only.
Every string will start from www. and end with .com, so well!


Sample Input
(Plaintext Link)

2
www.google.com
www.hackerearth.com

Sample Output
(Plaintext Link)

7/14
11/19

import java.util.Scanner;

public class TheBestInternetBrowser
{
public static void main(String[] args)
       {
Scanner scn=new Scanner(System.in);
int s=scn.nextInt();
String [] arr=new String[s];
for(int i=0;i<arr.length;i++)
{
arr[i]=scn.next();
}
for(String str:arr)
{
filter(str);
}

}
public static void filter(String s)
{
char l;
String nw="";
boolean b= false;
for(int i=4;i<s.length();i++)
{
l=Character.toLowerCase(s.charAt(i));

if(b==false)
            {
if(l=='a' ||l=='e' ||l=='i' ||l=='o' ||l=='u')
{

}
else if(l=='.')
{
nw+=l;
b=true;
}
                    else
                   {
nw+=l;
}
}
else
             {
nw+=l;
}
 
}
System.out.println(nw);
System.out.println(nw.length()+"/"+s.length());

}
}

Saturday, July 4, 2015

Complete String Program From Hacker Earth Solution In Java

A string is said to be complete if it contains all the characters from a to z. Given a string, check if it complete or not.
Input
First line of the input contains the number of strings N. It is followed by N lines each contains a single string.
Output
For each test case print "YES" if the string is complete, else print "NO"
Constraints
1 <= N <= 10
The length of the string is at max 100 and the string contains only the characters a to z


Sample Input
(Plaintext Link)

3
wyyga
qwertyuioplkjhgfdsazxcvbnm
ejuxggfsts


Sample Output
(Plaintext Link)

NO
YES
NO


import java.util.Scanner;

public class CompleteString
 {
public static void main(String[] args)
        {

Scanner scn=new Scanner(System.in);
int s=scn.nextInt();
String [] str=new String[s];
for(int i=0;i<str.length;i++)
{
str[i]=scn.next();
}
for(String ns:str)
{
fltr(ns);
}

}
public static void fltr(String str)
{
String s=str.replaceAll(" ", "");
String s1="";
String s2="";

for(char j='a';j<='z';j++)
{
s2+=j;
}
for(int i=0;i<s.length();i++)
{

char c=Character.toLowerCase(s.charAt(i));
if(s1.indexOf(c)==-1)
{
s1+=c;
}

}

if(s1.length()==s2.length())
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
  }

}

Friday, July 3, 2015

Reverse Or Palindrome Of String In JAva

public class ReverseString
 {

public static void main(String[] args)
        {
String s="madam";
String s1="";
for(int i=s.length()-1;i>=0;i--)
{
s1+=s.charAt(i);
}
System.out.println(s1);
if(s.equalsIgnoreCase(s1))
{
System.out.println(" palindrom");
}
else
{
System.out.println("not palindrom");
}

}

}

Pangrams Problem Hacker Rank

Problem Statement
Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)
After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.
Given a sentence s, tell Roy if it is a pangram or not.
Input Format Input consists of a line containing s.
Constraints
Length of s can be at most 103 (1|s|103) and it may contain spaces, lower case and upper case letters. Lower case and upper case instances of a letter are considered the same.
Output Format Output a line containing pangram if s is a pangram, otherwise output not pangram.
Sample Input #1
We promptly judged antique ivory buckles for the next prize    
Sample Output #1
pangram
Sample Input #2
We promptly judged antique ivory buckles for the prize    
Sample Output #2
not pangram
Explanation
In the first test case, the answer is pangram because the sentence contains all the letters of the English alphabet.


import java.util.*;

public class Pangrams {

public static void main(String[] args) {

Scanner scn=new Scanner(System.in);
String str=scn.nextLine();
String s=str.replaceAll(" ", "");
String s1="";
String s2="";
if(s.length()<1000 && s.length()>0)
{
for(char j='a';j<='z';j++)
{
s2+=j;
}
for(int i=0;i<s.length();i++)
{
char c=Character.toLowerCase(s.charAt(i));
if(s1.indexOf(c)==-1)
{
s1+=c;
}
}
if(s1.length()==s2.length())
{
System.out.println("pangram");
}
else
{
System.out.println("not pangram");
}
  }
else{
System.out.println(" your string length is max than limit . you can type only 1000 char");
}

}
}