Saturday, December 20, 2014

Falling in love with InteliJ Idea Community IDE

The local file history that keeps a track on my changes to a file, I am all smiles now! :~)

Local History - Click on the image to enlarge

Tuesday, May 20, 2014

Java Map/Collections Cheat Sheet : Simply 'When and What to use'?

This is a notoriously simple when and what to use Java collection API cheat sheet, containing most common implementations.

Monday, May 19, 2014

Find the occurrence of words in a given string

IDEONE: http://ideone.com/9SENHc
package com.learning.collection;
import java.util.*;
/**
 * Count frequency of words occurring in a string
 */
public class MapExample {
    public static void main(String[] args){
        String str = "ika pika ting tong ting tong me";
        String[] strr = str.split("\\s");
        workMap(strr);
    }

    static void workMap(String...words){
        Map map = new HashMap();
        Integer ONE = new Integer(1);

        for(String word : words){
            Integer frequency = (Integer)map.get(word);
            /*
            'frequency' is the count of the words.
            For a new word getting added to the Map, we set its frequency as 1.
            For existing words, we take their existing frequency (value in the map)
            and increment it and put back into the map correspondint to that word (key in the map)
             */
            frequency = (frequency == null) ? ONE : new Integer(frequency.intValue() + 1);
            map.put(word, frequency);
        }
        System.out.println("Unsorted:");
        System.out.println(map);

        Map sortedMap = new TreeMap(map);
        System.out.println("Sorted:");
        System.out.println(sortedMap);
    }
}
Output:
Unsorted: {ika=1, pika=1, ting=2, tong=2, me=1}
Sorted: {ika=1, me=1, pika=1, ting=2, tong=2}


--Suggestion by Dr. Heinz Kabutz (Java Champion)
How you would count words in Java 8 :-) And if you want to do it in parallel, just add parallel() into the stream...
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class MapExample {
  public static void main(String[] args) {
    String str = "hello world how are you how is life i am into ascent";

    Map<String, Integer> map = Arrays.stream(str.split("\\s"))
        .collect(Collectors.toMap(
            Function.identity(),
            n -> 1,
            (n1, n2) -> n1 + n2,
            TreeMap::new));
    System.out.println("map = " + map);
  }
}

Wednesday, April 30, 2014

Finding the JAR files which contain a specific .class file on Linux machine

This program searches through all .jar files in the current directory, and in any sub-directories, looking for the class that you specify. This can be very handy if you need to use a class in a Java program, but aren't sure which .jar file contains it.

Logic of script: The key is to get a list of all the jar files in present directory, open each jar archive and search it with our input classname, and for all positive output, print the name of the jar file on screen.

Thursday, April 24, 2014

Synchronization in Java : class and object locking concept

People talk about two types of multi-threaded locking - object and class. In my knowledge, locking is done on objects only. Let me explain.

Case 1: On objects we create using new or factory methods etc.
void synchronized myMethod(Type param) {
  //will lock on the instance used to call this method
}
or
synchronized(this) {
 //will lock on current object
}
or
synchronized(obj1) {
 //will lock on specified obj1 object
}

Monday, April 21, 2014

Writing singleton classes in Java

Singleton classes are those classes which can be instantiated only once. We need to restrict the creation of multiple instances of that class by blocking constructor access using new keyword etc, and instead regulate the incoming instance requests by creating the instance only once and return the same instance time and again on multiple calls.
Where do we actually need this singleton design pattern?

Friday, April 11, 2014

Bubble Sorting in Java

Bubble sorting sorts the array in-place bubbling up the largest value.
Complexity:
Worst case - O(n^2); average case - O(n^2); best case - O(n)

Visualization: (src. Wiki)

Thursday, March 20, 2014

Fibonacci Series in Java


Q. Print Fibonacci series in Java.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
public class FibonacciSeries {
  
 public static void main(String[] args) {
  int sum = 0;
  //how many numbers to print
  for(int i=0, j=1; i<=10; i++){
   if(i==0){
    //for printing first number which is 0
    System.out.print(0 + ", ");
   }
   else{
    //j has last 'sum', and sum now stores latest added value
    //while the control enters again, j gets latest 'sum' value before
    //new sum is calculated and printed again
    sum = j + (j=sum);
    System.out.print(sum + ", ");
   }
  }
 }
}

Thursday, January 30, 2014

Matrix Multiplication in Java


package com.learning.ds.matrices;
import com.learning.ds.arrays.ArrayUtil;

/**
 * Created by Rajdeep on 28/1/14.
 */
public class MatrixMultiplicationDemo {
    public static void main(String[] args){
        //the temp1 and temp2 array values can be changed to test this program
        int[][] temp1 = {{2,0}};
        int[][] temp2 = {{1,1,1}, {2,2,2}};

        System.out.println("Matrix 1: ");
        ArrayUtil.print2DIntArray(temp1);
        System.out.println("Matrix 2: ");
        ArrayUtil.print2DIntArray(temp2);

        if( !( isFilledMatrix(temp1) && isFilledMatrix(temp2) ) ){
            System.out.println("One of the matrices is not filled completely and can't be used for multiplication.");
        }
        else{
            //check dimension
            if(!areMatricesMultipliable(temp1, temp2)){
                System.out.println("The number of columns in first matrix is unequal to number of rows in second matrix. The must be equal for dot product.");
            }
            else{
                System.out.println("can be multiplied");
                int[][] tempNew = multiplyMatrices(temp1, temp2);
                System.out.println("new matrix is: ");
                ArrayUtil.print2DIntArray(tempNew);
            }
        }
    }

    private static int[][] multiplyMatrices(int[][] temp1, int[][] temp2) {
        //
        int rowCount1 = temp1.length;
        int colCount1 = temp1[0].length;
        int colCount2 = temp2[0].length;

        int[][] tempNew = new int[rowCount1][colCount2];

        for(int i=0; i < rowCount1; i++){
            int k=0;
            while(k < colCount2){
                int tempVal = 0;
                for (int j=0; j < colCount1; j++){
                    tempVal = tempVal + ( temp1[i][j] * temp2[j][k] );
                }
                tempNew[i][k] = tempVal;
                k++;
            }

        }

        return tempNew;
    }

    //matrix multiplication rule is
    //no of columns of left matrix == no of rows in right matrix
    // (m x n) . (n x p) = (m x p)
    private static boolean areMatricesMultipliable(int[][] mat1, int[][] mat2){
        return (mat1[0].length == mat2.length);
    }

    //check the matrix has all elements filled or not
    //In other words, checking whether number of columns in each row is same
    private static boolean isFilledMatrix(int[][] mat){
        boolean retVal = false;
        int rows = mat.length;
        
        if(rows == 1){
            retVal = true;
        }
        else {
            for(int i=0; i < (rows-1); i++){
                if(mat[i].length != mat[i+1].length){
                    retVal = false;
                    break;
                }
                else
                    retVal = true;
            }
        }

        return retVal;
    }
}


The
ArrayUtil.print2DArray(int[][] args)
prints the array on screen through normal 'for' loops.
One sample output:
Matrix 1:
2 0
Matrix 2:
1 1 1
2 2 2
can be multiplied
new matrix is:
2 2 2
Another sample output by changing the temp1 and temp2 arrays in main() method:
Matrix 1::
2 0 3:
Matrix 2::
1 1 1:
2 2 2:
One of the matrices is not filled completely and can't be used for multiplication.

Monday, January 27, 2014

Matrix Operation in Java: Addition of two 2x2 matrices demonstrated


For addition or subtraction, the dimensions of the matrices must be same. This is just a demonstration code and can be rewritten in a far more optimized manner.
package com.learning.ds.matrices;

/**
 * Created by Rajdeep on 27/1/14.
 */
public class MatrixAdditionDemo {
    public static void main(String[] args){
        int[][] arr1 = {{1,2,3},{4,2,6}};
        int[][] arr2 = {{10,20,30},{40,50,60}};

        System.out.println("Matrix A:");
        for(int i=0; i < arr1.length; i++){
            for(int j=0; j < arr1[i].length; j++){
                System.out.print(arr1[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("Matrix B:");
        for(int i=0; i < arr2.length; i++){
            for(int j=0; j < arr2[i].length; j++){
                System.out.print(arr2[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("Addition of A and B:");
        int[][] tempArr = addMatrices(arr1,arr2);
        if(tempArr!=null){
            for(int i=0; i < tempArr.length; i++){
                for(int j=0; j < tempArr[i].length; j++){
                    System.out.print(tempArr[i][j] + " ");
                }
                System.out.println();
            }
        }

    }

    //add the matrices
    private static int[][] addMatrices(int[][] m1, int[][] m2){
        //check size
        if(!ofSameSize(m1, m2)){
            System.out.println("[Error] The matrices' dimension in operation do not match!");
            return null;
        }
        int len1 = m1.length;
        int[][] tempArr = new int[2][3];
        for(int i=0; i < tempArr.length; i++){
            for(int j=0; j < tempArr[i].length; j++){
                tempArr[i][j] = m1[i][j] + m2[i][j];
            }
        }
        return tempArr;
    }

    //for adding, the size must be same
    private static boolean ofSameSize(int[][] m1, int[][] m2) {
        int len1 = m1.length;
        int len2 = m2.length;
        boolean check = true;
        if(len1==len2 & len1!=0){
            //System.out.println("length is: " + len1 + " and " + len2);
            for(int i=0; i < len1; i++){
                if(!(m1[i].length == m2[i].length)){
                    check = false;
                }
            }
        }
        else
            check = false;

        return check;
    }
}

Sample output 1:
Matrix A:
1 2 3
4 2 6
Matrix B:
10 20 30
Addition of A and B:
[Error] The matrices' dimension in operation do not match!

Sample output 2:
Matrix A:
1 2 3
4 2 0 
 
Matrix B:
10 20 30
11 5 3 
 
Addition of A and B:
11 22 33
15 7 3 

Quick Sort Demo


This is a divide and conquer approach. Take a pivot as the last element of array, and place all numbers lesser than this to the left. This is done using partitioning as seen in the code.
Complexity:
Best - O(n logn); Average - O(n logn); Worst - O(n^2)