Tuesday, 24 November 2015

Print Natural numbers using two Even-Odd printing Thread

Print Natural numbers using Even-Odd Thread

There are two Threads, one Thread will print the even sequence and another will print the Odd sequence.
Use these Threads to print the sequence in the natural order.

PrintOdd.java
class PrintOdd implements Runnable {
     public static boolean oddFlag = true;
     public void run() {
           for (int i = 1; i <= 9;) {
                if (oddFlag) {
                     System.out.print(i+" ");
                     oddFlag = false;
                     i = i + 2;
                }
           }
     }
}

PrintEven.java
class PrintEven implements Runnable {
     public void run() {
           for (int i = 2; i <= 10;) {
                if (!PrintOdd.oddFlag) {
                     System.out.print(i+" ");
                     PrintOdd.oddFlag = true;
                     i = i + 2;
                }
           }
     }
}

PrintNatural.java
public class PrintNatural {
     public static void main(String args[]) {
           PrintEven prEven = new PrintEven();
           PrintOdd prOdd = new PrintOdd();
           Thread evenThread = new Thread(prEven);
           Thread oddThread = new Thread(prOdd);
           evenThread.start();
           oddThread.start();
     }
}
Output:
1
2
3
4
5
6
7
8
9
10

Thursday, 19 November 2015

How to get the name of the current executing method in java?

Using reflection:


/** using reflection trace. */
Method method = new Object(){}.getClass().getEnclosingMethod();
String methodName = method.getName();


However, a new anonymous inner class will be created during compile time (e.g. MethodNameTest$1.class). So this will create a .class file for each method that deploys this trick.

Advantage of trick is that getEncosingMethod()

It returns java.lang.reflect.Method which can be used to retrieve all other information of the method including annotations and parameter names. This makes it possible to distinguish between specific methods with the same name (method overload).

Using stackTrace:

/** using stack trace. */
StackTraceElement[]stackTrace=Thread.currentThread().getStackTrace()
String nameUsingTrace = stackTrace[1].getMethodName();



import java.lang.reflect.Method;

public class MethodNameTest {
     public static void main(String[] args) {
           checkMethodName();
     }

     private static void checkMethodName() {
           /** using stack trace. */
           StackTraceElement[] stackTrace =                 
                       Thread.currentThread().getStackTrace();
           String nameUsingTrace = stackTrace[1].getMethodName();
          
           System.out.println("print method name using stack trace : "
                     + nameUsingTrace);

           /** using reflection trace. */
           Method method =
                 new Object(){}.getClass().getEnclosingMethod();

           String methodName = method.getName();

           System.out.println("print method name using reflection : "
                     + methodName);
     }
}
Output:
print method name using stack trace : checkMethodName
print method name using reflection : checkMethodName

Wednesday, 18 November 2015

ArrayList vs HashMap in Java


ArrayList
HashMap
Interface
Implementation of java.util.List Interface.
Implementation of java.util.Map interface.

Storage
It used to store the object.
It is used to store the object in key-value pair.
Where key and value are different objects.

Methods to implement
No method is required to implement.

However contains() method uses the equals() method to check the existence of the object.
For HashMap, class which is used as key must implements equals() and hashCode() method correctly.

Better hashcode() implementation will lead to better performance.

Ordering
ArrayList maintain order of object.
HashMap doesn't provide any order guarantee.

Duplicate
ArrayList allows duplicates
HashMap doesn't allow duplicates key, though it allows duplicate values.

Resizing
Size increase 50% after resizing.
Size increase 100%. Load factor plays the vital role to resize the HashMap.

Tuesday, 17 November 2015

Array vs ArrayList


Array
ArrayList
Size
Array is a fixed length data structure.

Length of array cannot changed once it created.
ArrayList is a variable length Collection class.
Resizing operation in ArrayList is slow down performance as it creates new Array and copying content from old Array to new Array.

Generics
Array doesn’t support the Generics, as Array instance knows about what kind of type it can hold and throws ArrayStoreException.

ArrayList allows you to use Generics to ensure type-safety.

Wrapper
Array allows to store both primitives and Objects in Java.
ArrayList doesn’t allow to store primitives in ArrayList, it can only contain Objects.

ArrayList<Integer> integerList = new ArrayList<Integer>();

integerList.add(1);
Primitive data type will be autobox into the Integer object while storing.

Size
Initialize
We can create instance of ArrayList without specifying size.

It is mandatory to provide size of Array while creating.
Multi-dimensional
Array can be multi-dimensional.

Array list is single dimensional.
Performance
Fast.

Slow because resizing.
Iterator
Using for, foreach
Using foreach, Iterator, List Iterator.

Pancake sort in java

Pancake sort:

Pancake sorting is the colloquial term for the mathematical problem of sorting a disordered stack of pancakes in order of size when a spatula can be inserted at any point in the stack and used to flip all pancakes above it.

A pancake number is the maximum number of flips required for a given number of pancakes.


flip(array, i): Reverse array from 0 to i.


Pseudo code Pancake sort:

1) iMax = Index of Largest element in unsorted array.
Find index of the maximum element index in arr[0..unsorted_array_size -1].

2) Call flip(array, iMax)
It will flip all element of array from 0 to iMax index.
The largest element will be the first element in the array.

3) Call flip(array, unsorted_array_size -1)
Flip complete unsorted array which result to put the largest element at the end of the unsorted array.


Complexity :
Total O(n) flip operations are performed in where each flip will take O(n) time. Therefore complexity is O(n^2).

Example
19
23
6
15
45
30
14

1. Find Max element index from 0 to N-1
iMax = 4
19
23
6
15
45
30
14

2. flip(0,iMax)
45
15
6
23
19
30
14

3. flip(0,N-1)
14
30
19
23
6
15
45

Repeat Step #1 to Step #3:
1. Find Max element index from 0 to N-2
iMax = 1
14
30
19
23
6
15
45

2. flip(0,iMax)
30
14
19
23
6
15
45

3. flip(0,N-2)
15
6
23
19
14
30
45

class PancakeSort {

     /**Perform Pancake sort. */
     static int pancakeSort(int array[]) {

           int n = array.length;
           /** */
           for (int unsortASize=n; unsortASize>1;--unsortASize) {
                /**
                 * Find index of the maximum element
                 * in arr[0.. unsortArrSize-1]
                 * */
                int idxMax = findMax(array,unsortASize);
               
                /**
                 * Move the maximum element to end of current
                 * array if it's not already at the end*
                 */
                if (idxMax != unsortASize-1) {
                    
                     /**flip will put the max element to beginning.*/
                     flip(array, idxMax);

                     /**
                      * flip will put the max element in the last
                      * of unsorted array.
                      **/
                     flip(array, unsortASize-1);
                }
           }
           return 0;
     }

     /**
      * Returns index of maximum element in unsorted array.
      **/
     static int findMax(int array[], int n) {
           int idxMax = 0;
           for (int i = 0; i < n; ++i) {
                if (array[i] > array[idxMax]) {
                     idxMax = i;
                }
           }
           return idxMax;
     }

     /**
      * Reverses array[0..idx].
      **/
     static void flip(int array[], int idx) {
           int temp, start = 0;
           while (start < idx) {
                temp = array[start];
                array[start] = array[idx];
                array[idx] = temp;
                start++;
                idx--;
           }
     }

     /** Utility function: print array*/
     static void printArray(int arr[]) {
           StringBuilder sb = new StringBuilder();
           for (int element : arr) {
                sb.append(element).append(" ");
           }
           System.out.println(sb.toString());
     }

     /** Test Pancake sort. */
     public static void main (String[] args) {
           int array[] = {23, 10, 20, 11, 12, 6, 7};
          
           System.out.println("Unsorted Array: ");
           printArray(array);
          
           PancakeSort.pancakeSort(array);
          
           System.out.println("Sorted Array: ");
           printArray(array);
     }

}

Output:
     Unsorted Array:
     23 10 20 11 12 6 7
     Sorted Array:
     6 7 10 11 12 20 23
Related Posts Plugin for WordPress, Blogger...