Saturday, 31 October 2015

Reversing an array(shortest method)

import java.util.Scanner;
class ReverseArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
System.out.println("array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+"\t");
for(int i=0;i<n/2;i++)
{
int temp=arr[i];
arr[i]=arr[arr.length-1-i];
arr[arr.length-i-1]=temp;
}
System.out.println("reverse array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+"\t");
}
}

Removing Duplicates From Array

import java.util.Scanner;
class Duplicate
{
void removeDuplicate(int arr[])
{
int size=arr.length;
for(int i=0;i<size-1;i++)
{
for(int j=i+1;j<size;j++)
{
if(arr[i]==arr[j])
{
while(j<size-1)
{
arr[j]=arr[j+1];
j++;
}
size--;
}
}
}
for(int i=0;i<size;i++)
System.out.println(arr[i]);
}
}
class DuplicateTest
{
public static void main(String args[])
{
Duplicate d1=new Duplicate();
Scanner sc=new Scanner(System.in);
System.out.println("enter the values of n:");
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
d1.removeDuplicate(arr);
}
}

Perfect Number

import java.util.Scanner;
class Perfect
{
void findPerfect(int n)
{
int temp=n;
int sum=0;
for(int i=1;i<=n/2;i++)
{
if(n%i==0)
sum=sum+i;
}
if(temp==sum)
System.out.println("Perfect");
else
System.out.println("Not a Perfect");
}
}
class PerfectTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Perfect d1=new Perfect();
int number=sc.nextInt();
d1.findPerfect(number);
}
}

Armstrong Number

import java.util.Scanner;
class Armstrong
{
void findArmstromg(int n)
{
int temp=n;
int r=0;
int sum=0;
while(n>0)
{
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(temp==sum)
System.out.println("Armstrong");
else
System.out.println("Not a Armstrong");
}
}
class ArmstrongTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Armstrong d1=new Armstrong();
int number=sc.nextInt();
d1.findArmstromg(number);
}
}

swapping two numbers without using third variable

import java.util.Scanner;
class Swap
{
void swap1(int a,int b)
{
a=a+b;
b=a-b;
a=a-b;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap2(int a,int b)
{
a=a^b;
b=a^b;
a=a^b;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap4(int a,int b)
{
a=a+b-(b=a);
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap5(int a,int b)
{
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}

}
class SwapTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
Swap s1=new Swap();
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
s1.swap1(a,b);
s1.swap2(a,b);
s1.swap5(a,b);
s1.swap4(a,b);
}
}

Reverse of a number

import java.util.Scanner;
class Reverse
{
void printReverse(int number)
{
int r=0;
int reverse=0;
while(number>0)
{
r=number%10;
reverse=reverse*10+r;
number=number/10;
}
System.out.println(reverse);
}
}
class ReverseTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
Reverse m1=new Reverse();
m1.printReverse(number);
}
}

Greatest of three numbers

import java.util.Scanner;
class Maximum
{
void printMaximum(int a,int b,int c)
{
int max=a;
if(b>max)
max=b;
if(c>max)
max=c;
System.out.printf("maximum is %d",max);
}
}
class MaximumTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
Maximum m1=new Maximum();
m1.printMaximum(a,b,c);
}
}

Factorial(with or without recursion)

import java.util.Scanner;
class Factorial
{
void printFactorial(int number)
{
int fact=1;
for(int i=1;i<=number;i++)
fact=fact*i;
System.out.println(fact);
}
int printFactorialRecursion(int number)
{
if(number==0)
return 1;
else
return number*printFactorialRecursion(number-1);
}
}
class FactorialTest
{
public static void main(String args[])
{
Factorial f1=new Factorial();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
f1.printFactorial(n);
int t=f1.printFactorialRecursion(n);
System.out.println(t);
}
}

Fibonacci series

import java.util.Scanner;
class Fibonacci
{
//this will find  Fibonacci upto the maximum number given
void printSeries(int number)
{
int sum=0;
int a=1;
int b=1;
System.out.printf("%d%d",a,b);
while(sum<number)
{
sum=a+b;
System.out.print(sum);
b=a;
a=sum;
}
}
//this will find Fibonacci upto n terms
int fibrecursion(int number)
{
if(number==0||number==1)
return 1;
else
return fibrecursion(number-1)+fibrecursion(number-2);
}
}
class FibonacciTest
{
public static void main(String args[])
{
Fibonacci f1=new Fibonacci();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
//f1.printSeries(n);
for(int i=0;i<n;i++)
{
int t=f1.fibrecursion(i);
System.out.println(t);
}
}
}

Find gcd of two numbers

import java.util.Scanner;
class Gcd
{
void toFindGcd(int number1,int number2)
{
while(number1!=number2)
{
if(number1>number2)
number1=number1-number2;
else
number2=number2-number1;
}
System.out.printf("gcd of these two numbers is: %d",number1);
}
}
class GcdTest
{
public static void main(String args[])
{
Gcd g1=new Gcd();
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
g1.toFindGcd(n1,n2);
}
}

Check whether a given string is palindrome or not

//It can be done by three methods.
import java.util.Scanner;
class Palindrome
{
private boolean found=true;
void palByLogic(String s1)
{
char a[]=new char[s1.length()];
a=s1.toCharArray();
for(int i=0;i<s1.length()/2;i++)
{
if(a[i]!=a[s1.length()-i-1])
{
found=false;
break;
}
}
if(found==false)
System.out.println("not a palindrome:");
else
System.out.println("palindrome:");
}
void palByStBuffer(String s1)
{
StringBuffer s2=new StringBuffer(s1);
String s3=s2.reverse().toString();
if(s1.equals(s3))
System.out.println("Palindrome:");
else
System.out.println("Not a Palindrome:");
}
void palByStBuiler(String s1)
{
StringBuilder s2=new StringBuilder(s1);
String s3=s2.reverse().toString();
if(s1.equals(s3))
System.out.println("Palindrome:");
else
System.out.println("Not a Palindrome:");
}
}
class PalindromeTest
{
public static void main(String args[])
{
Palindrome p1=new Palindrome();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String:");
String s1=sc.next();
p1.palByLogic(s1);
p1.palByStBuffer(s1);
p1.palByStBuiler(s1);
}
}

Find all the prime numbers less than a given number

import java.util.Scanner;
class BeforePrimeNumber
{
void checkBeforePrimeNumber(int number)
{
if(number==2)
System.out.print("2");
else
System.out.print(2+"\t"+3+"\t");
for(int j=4;j<number;j++)
{
boolean found=true;
for(int i=2;i*i<=number;i++)
{
if(j%i==0)
{
found=false;
}
}
if(found==true)
System.out.print(j+"\t");
}
}
}
class BeforePrimeNumberTest
{
public static void main(String args[])
{
BeforePrimeNumber p1=new BeforePrimeNumber();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number you want to insert:");
int n=sc.nextInt();
p1.checkBeforePrimeNumber(n);
}
}

Check whether a given number is prime or not.

import java.util.Scanner;
class CheckPrime
{
boolean found=true;
void checkCheckPrime(int number)
{
for(int i=2;i*i<number;i++)
{
if(number%i==0)
{
found=false;
break;
}
}
if(found==true)
System.out.println("number is Prime");
else
System.out.println("number is not Prime");
}
}
class CheckPrimeTest
{
public static void main(String args[])
{
CheckPrime p1=new CheckPrime();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number you want to insert:");
int n=sc.nextInt();
p1.checkCheckPrime(n);
}
}

Monday, 19 October 2015

java quizs

java quiz-3

java quiz-3



1
suppose you have  taken input as x=96 y=96.35 and s=java
what will be the output?
import java.util.Scanner;

public class Solution
{
public static void main(String[] args)
{
            Scanner sc=new Scanner(System.in);
            int x=sc.nextInt();
            double y=sc.nextDouble();
            String s=sc.nextLine();
            System.out.print(x);
            System.out.print(y);
            System.out.print(s);
}
}

9696.35java
96 96.35 java
CompileError
9696.35

2
class Wrap
{
public static void main(String args[])
{
Boolean b1=new Boolean("java");
System.out.println(b1);
}
}
java
false
true
compileError


3
class String_Check
{
public static void main(String args[])
{
String s1=new String();
System.out.print(s1);
}
}
null
no output
String_Check@15db9742
compile error


4
class String_Check
{
public static void main(String args[])
{
String s3=null;
String s4=null;
System.out.println(s3.equals(s4));
}
}
null
true
false
a compile time exception


5
public class B extends A
{
private int bar;
public void setBar(int b)
{
bar = b;
}
}
class A {
public int foo;
}
class A is tightly encapsulated
class B is tightly encapsulated
class A and B is tightly encapsulated
neither class A nor class B is tightly encapsulated


6
class A
{
public void baz()
{
System.out.println("A");
}
}
class B extends A
{
public static void main(String [] args)
{
A a = new B();
a.baz();
}
public void baz() {
System.out.println("B");
}
}
A
B
compilation error
runtime exception


7
class ThreeConst
{
public static void main(String [] args)
{
new ThreeConst(4L);
}
public ThreeConst(int x) {
this();
System.out.print(" " + (x * 2));
}
public ThreeConst(long x) {
this((int) x);
System.out.print(" " + x);
}
public ThreeConst()
{
 System.out.print("no-arg ");
}
}
4
8 4 no-arg
no-arg 8 4
compile time error


8
int x;
x=n.test();
int test()
{
//line x
return y;
}
which line of code,inserted at line x,will not compile?
short y=7;
int y=(int)7.2d;
Byte y=7;
int y=0xface;


9
class Test
{
public static Foo f = new Foo();
 public static Foo f2;
 public static Bar b = new Bar();

 public static void main(String [] args)
 {
 for (int x=0; x<6; x++)
{
 f2 = getFoo(x);
 f2.react();
 }
 }
 static Foo getFoo(int y)
 {
 if ( 0 == y % 2 )
 {
 return f;
 }
else
{
 return b;
 }
 }
 }
 class Bar extends Foo
 {
 void react()
 {
 System.out.print("Bar "); }
 }
 class Foo {
 void react() { System.out.print("Foo "); }

 }
Bar Bar Bar Bar Bar Bar
Foo Bar Foo Bar Foo Bar
Foo Foo Foo Foo Foo Foo.
Compile error.


10
class Foo
{
String doStuff(int x) { return "hello"; }

}
which method would not be legal in a subclass of Foo?
 String doStuff(int  x) { return "hello"; }
 int doStuff(int x) { return 42; }
 public String doStuff(int x) { return "Hello"; }
 protected String doStuff(int x) { return "Hello"; }

Thursday, 24 September 2015

java quiz-2


java quiz-2



1
class Test
{
public static void main(String args[])
{
byte g=3;
switch(g)
{
case 3:
System.out.printf("java");
case 129:
System.out.printf("for");
}
System.out.printf("ocpjp");
}
}
java
javaforocpjp
CompileError
RunTimeException


2
class Test
{
boolean sum()
{
for(int i=0;i<3;i++)
{
System.out.printf("java");
return true;//line y
}
return false;//line x
}
public static void main(String args[])
{
Test t1=new Test();
boolean fp=t1.sum();
 }
}
java
javajavajava
compilation fails due to line x
compilation fails due to line y


3
class Test
{
public static void main(String args[])
{
int x=5;
switch(x)
{
case 1:
System.out.println("Nature");
break;
case 5:
System.out.println("Beauty");
continue;
}
System.out.println("AXXL");
}
}
Compilation fails
execute infinte times
Beauty AXXL
Beauty


4
class Test
{
public static void main(String args[])
{
int arr[]=new int[5];
try
{
for(int i=0;i<=5;i++)
System.out.printf(arr[i]);
}
catch(Exception e)
{
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
000000
012345
Compilation fails
An exception is thrown at run-time


5
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :go();
System.out.println(ans);
}
}
}
4321 for more information of the exception it will print baba
Runtime exception
4321
Compile Error


6
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static int go()
{
return 25;
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :go();
System.out.print(ans);
}
}
}
runtime exception
comile error
it will print 4321
it will print 4321 and for more information of the exception it will print 25


7
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :new Exc15();
System.out.print(ans);
}
}
}
it will print 4321 and for more information of the exception it will print hashcode of the object
it will print 4321 and terminate
it will print 4321 only
comile time error


8
public class Test {
public static void main(String [] args) {
int I = 1;
do while ( I < 1 )
System.out.print("I is " + I);
while ( I > 1 ) ;
}
}
compilation error at line 4
1
No output is produced
compilation error at line 6


9
1. import java.io.*;
2. public class MyProgram {
3. public static void main(String args[]){
4. FileOutputStream out = null;
5. try {
6. out = new FileOutputStream("test.txt");
7. out.write(122);
8. }
9. catch(IOException io) {
10. System.out.println("IO Error.")
11. }
12. finally {
13. out.close();
14. }
15. }
16. }
This program fails to compile due to an error at line 4.
This program fails to compile due to an error at line 13.
This program will compile successfully.
This program fails to compile due to an error at line 9.


10
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :Exc15 e
System.out.print(ans);
}
}
}
compile time error
1234
it will print 1234 and then print the refernce of class Exc15
runtime Exception

Wednesday, 23 September 2015

"assert" keyword in Java

The assert keyword is used in assert statement which is a feature of the Java programming language since Java 1.4. Assertion enables developers to test assumptions in their programs as a way to defect and fix bugs.

Syntax of assert statement:-

(short version):

assert expression1;
 or (full version):
assert expression1 : expression2;
  • expression1 must be a boolean expression.
  • expression2 must return a value (must not return void).
By default,assertion is disabled at runtime to enable assertion,specify the switch -ea or 
-enableassertions  at command line of java program.for example to enable assertion for the program IsTest
                                                 
                                                       java -enableassertions IsTest 
or this for short
                                                              java -ea IsTest

1. You can combine switches to say disbale assertions in single class but keep enabled for       all others.                         
                                 java -ea -da:com.geekanonymous.Foo
    
    the preceding command line tells the jvm keep the assertions enable in general and             disable it for class Foo.

2. You can enable the assertion or disable the assertion in the System class with the -esa         and -dsa flags.

3. if assertion statement is false then it will throw Assertion Error which you should never           handle.


class Exc15
{
static int n=5;
       static int sum()
      {
      return --n; 
      }
public static void main(String args[])
{
      for(int i=0;i<=10;i++)
      {
      int ans=sum();
      assert ans>0;
     //assert ans>0 :"negative number";//give more information
     System.out.println(ans);
      }
}
}
 

  

Friday, 18 September 2015

Counting Sort

In this sort, we count the frequencies of distinct elements of array and store them in an auxiliary array, by mapping its value as index of auxiliary array and then place each element in its proper position in the output array .
Complexity: As the above code runs in linear time so the complexity in worst case will be O(max + n), where n is the number of elements and max is the range of input element of array A[ ].


import java.util.Scanner;
class Count
{
void sort(int a[])
{
int max=a[0];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
max=a[i];
}
int count[]=new int[max+1];
int output[]=new int[a.length];
for(int i=0;i<a.length;i++)
count[a[i]]++;
for(int i=1;i<count.length;i++)
count[i]=count[i]+count[i-1];
for(int i=0;i<a.length;i++)
{
output[count[a[i]]-1]=a[i];
count[a[i]]=count[a[i]]-1;
}
System.out.println("the sorted array is:");
for(int i=0;i<output.length;i++)
System.out.println(output[i]+"\t");
}
}
class CountTest
{
public static void main(String args[])
{
Count c1=new Count();
System.out.println("enter the total number of elements:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d element:",(i+1));
arr[i]=sc.nextInt();
}
c1.sort(arr);
}
}


Thursday, 17 September 2015

Quick Sort

Quick Sort: This algorithm is also based on the divide and conquer approach. It reduces the space complexity and removes the use of auxiliary array used in merge sort.
Idea: It is based on the idea of choosing one element as pivot element and partitioning the array around it such that the left side of pivot contains all elements less than the pivot element and right side contains all elements greater than the pivot.
Selecting a random pivot in an array results into an improved time complexity in average cases.
Implementation:
Choose the first element of array as pivot element First, we will see how the partition of the array takes place around the pivot.


Example: you have an array A[]={9,7,8,3,2,1}.






import java.util.Scanner;
class Quick
{
void sort(int a[],int start,int end)
{
if(start<end)
{
int pos=partition(a,start,end);
sort(a,start,pos);
sort(a,pos+1,end);
}
}
int partition(int a[],int start,int end)
{
int piv=a[start];
int pindex=start+1;
for(int i=start+1;i<end;i++)
{
if(a[i]<=piv)
{
int temp=a[i];
a[i]=a[pindex];
a[pindex]=temp;
pindex=pindex+1;
}
}
pindex=pindex-1;
int x=a[pindex];
a[pindex]=a[start];
a[start]=x;
return pindex;
}
}
class QuickTest
{
public static void main(String args[])
{
Quick q1=new Quick();
Scanner sc=new Scanner(System.in);
System.out.println("enter the total number of elements:");
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d elements:",(i+1));
arr[i]=sc.nextInt();
}
q1.sort(arr,0,n);
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}
Complexity:The worst case time complexity of this algorithm is O(n2),but as this is randomized algorithm,its time complexity fluctuates between O(n2) and O(n(log n) ) and mostly it comes out to be O(n(log n)) .



Wednesday, 16 September 2015

Merge Sort

Merge Sort: This sorting algorithm works on the following principle - Divide the array in two halves. Repeatedly sort each half, then merge two halves.
Lets say we have an array A[ ] = { 9, 7, 8, 3, 2, 1} .
First we will divide it in two halves A1 [ ] = {9, 7, 8} and A2[ ] = {3, 2, 1}. Again divide these 2 halves in their two halves. For A1 it will be A1_a[ ] = {9, 7} and A1_b[ ] = {8}. Again, divide A1_a and then as they further cannot be divided, so merge them by comparing them. A1_a will be {7, 9} and then compare and merge A1_a and A1_b. Now, A1 will be { 7, 8, 9} . Do same for A2 and then A2 will be {1, 2, 3} . Now, compare A1 and A2 and then merge them. Now, A will be {1, 2, 3, 7, 8, 9}.

complexity:Array with n elements is divided recursively in 2 parts, so it will form a tree with nodes asdivided parts of array (subproblems).The height of the tree will be log2n and at each level of tree the computation cost of all the subproblems will be n. At each level the merge operation will take O( n) time.So the overall complexity of this algorithm will be O( n(log2 n)).



Here in merge function, we will merge the two part of arrays where one part has starting and ending positions from start to mid respectively and another part has positions from mid+1 to end.
We will start from starting positions of both the parts that are p and q.Then we will compare respective elements of both the parts and the one with the smaller value will be stored in the auxiliary array. If at some condition ,one part comes to end ,then all the elements of another part of array are added in the auxiliary array in the same order they exist.





import java.util.Scanner;
class Merge
{
void sort(int arr[],int n)
{
int left[];
int right[];
if(arr.length<2)
return;
int mid=arr.length/2;
left=new int[mid];
right=new int[arr.length-mid];
for(int i=0;i<mid;i++)
left[i]=arr[i];
for(int i=mid;i<n;i++)
right[i-mid]=arr[i];
sort(left,left.length);
sort(right,right.length);
Merge m2=new Merge();
m2.merge(arr,right,left);
}
void merge(int arr[],int right[],int left[])
{
int i=0,k=0,j=0;
while(i<left.length && j<right.length)
{
if(left[i]<=right[j])
{
arr[k]=left[i];
k++;
i++;
}
else
{
arr[k]=right[j];
k++;
j++;
}
}
while(i<left.length)
{
arr[k]=left[i];
k++;
i++;
}
while(j<right.length)
{
arr[k]=right[j];
k++;
j++;
}
}
}
class MergeTest
{
public static void main(String args[])
{
Merge m1=new Merge();
Scanner sc=new Scanner(System.in);
System.out.println("enter the total number of elements:");
int n=sc.nextInt();
int a[]=new int [n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d elements:",i+1);
a[i]=sc.nextInt();
}
m1.sort(a,n);
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
System.out.print(a[i]+"\t");
}
}