Tuesday, 15 September 2015

Count all possible paths from top left to bottom right of a m*n Matrix


A person starts from the uppermost, leftmost corner of a grid. Each cell of grid is 0,1,2,3,4,5,6 or 7. From any cell, he can only go to right cell if this cell is 1, he can only go to lower cell if this cell is 2, he can only go to its diagonally opposite cell if this cell is 3, he can go to right and lower cell if this cell is 4, he can go to right and diagonally opposite cell if this cell is 5, he can go to lower and diagonally opposite cell if this cell is 6, he can go to right and lower and diagonally opposite cell if this cell is 7 and he can not move from this cell if this cell is 0. The following figure shows each of these cases:

Person wants to go to the lowermost, rightmost corner of the grid. You have to find number of paths travelling on which he can reach at destination.

Input :
Input1: An Integer array having  two elements: m, n that depict rows and columns of the grid respectively
Input2: An Integer array containing m*n elements 

Output :
Output will be the number of ways to reach the ending position.

For Example:-
Input1: 4 6
Input2: 1 3 0 0 0 0 0 0 4 5 1 0 0 0 0 6 7 6 0 0 0 0 5 0

Output: 3

Input1: 3 4
Input2: 1 2 0 0 5 0 0 0 7

Output: 1

Note:Press Enter after each input for ex: after entering 4 press enter then enter 6 as scanner nextInt method is used for reading input.

Solution:

import java.util.Scanner;  
 public class MatrixPathProblem {  
      int m, n;  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           MatrixPathProblem obj = new MatrixPathProblem();  
           int a[] = new int[2];  
           Scanner s = new Scanner(System.in);  
           for (int i = 0; i < a.length; i++) {  
                a[i] = s.nextInt();  
           }  
           obj.m = a[0];  
           obj.n = a[1];  
           int b[] = new int[obj.m * obj.n];  
           for (int i = 0; i < b.length; i++) {  
                b[i] = s.nextInt();  
           }  
           int mat[][] = new int[obj.m][obj.n];  
           int k = 0;  
           for (int i = 0; i < obj.m; i++) {  
                for (int j = 0; j < obj.n; j++) {  
                     mat[i][j] = b[k];  
                     k++;  
                }  
           }  
           System.out.println(obj.path(mat, 0, 0));  
      }  
      private int path(int[][] a, int i, int j) {  
           if (i == m - 1 && j == n - 1)  
                return 1;  
           else if (i == m - 1) {  
                if (a[i][j] == 0)  
                     return 0;  
                else  
                     return 1;  
           } else if (j == n - 1) {  
                if (a[i][j] == 0)  
                     return 0;  
                else  
                     return 1;  
           } else if (a[i][j] == 0)  
                return 0;  
           else if (a[i][j] == 1)  
                return path(a, i, j + 1);  
           else if (a[i][j] == 2)  
                return path(a, i + 1, j);  
           else if (a[i][j] == 3)  
                return path(a, i + 1, j + 1);  
           else if (a[i][j] == 4)  
                return path(a, i + 1, j) + path(a, i, j + 1);  
           else if (a[i][j] == 5)  
                return path(a, i, j + 1) + path(a, i + 1, j + 1);  
           else if (a[i][j] == 6)  
                return path(a, i + 1, j) + path(a, i + 1, j + 1);  
           else if (a[i][j] == 7)  
                return path(a, i, j + 1) + path(a, i + 1, j + 1)  
                          + path(a, i + 1, j);  
           else  
                return 0;  
      }  
 }  

Tuesday, 8 September 2015

Java Program to Find Lexicographically Smallest and Largest substring of Length K


What is Lexicographic order?

Lexicographic order is an order in which words are displayed in alphabetical order using the appearance of letters in the word.It is also know as dictionary order or alphabetical order.For ex:-"Africa" is smaller than "Bangladesh" ,"He" is smaller than "he".

Sample program:-

 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 import java.util.Scanner;  
 /**  
  * @author Dixit  
  *   
  */  
 public class LexicographicExample {  
      public static void main(String a[]) {  
           Scanner sc = new Scanner(System.in);  
           System.out.println("Enter the String:-");  
           String str = sc.nextLine();  
           System.out.println("Enter the length");  
           int count = sc.nextInt();  
           List<String> list = new ArrayList<String>();  
           for (int i = 0; i < str.length(); i = i + 1) {  
                if (str.length() - i >= count) {  
                     list.add(str.substring(i, count + i));  
                }  
           }  
           Collections.sort(list);  
           System.out.println("Smallest subString:-" + list.get(0));  
           System.out.println("Largest subString:-" + list.get(list.size() - 1));  
      }  
 }  


 Output  
 Enter the String:-  
 helloworld  
 Enter the length  
 2  
 Smallest subString:-el  
 Largest subString:-wo  


Enjoy programming.

Tuesday, 1 September 2015

ListenerExecutorService and its Example



What is ListenerExecutorService ?
ListenerExecutorService is almost same as ExecutorService except  in ListenerExecutorService ,callback methods can be registered and that will be called once execution of task reach some defined state.ListenerExecutorService returns ListenableFuture instances.ListenableFuture instance allows to register callback methods which will get executed once the task gets completed.

In order to create ListenerExecutorService ,you need to use decorator which accepts ExecutorService as parameter
                MoreExecutors.listeningDecorator(ExecutorService);
You can use any of the ExecutorService (newFixedThreadPool(),newSingleThreadExecutor(),etc)


Sample Example:-


 import java.util.concurrent.Callable;  
 import java.util.concurrent.Executors;  
 import com.google.common.util.concurrent.FutureCallback;  
 import com.google.common.util.concurrent.Futures;  
 import com.google.common.util.concurrent.ListenableFuture;  
 import com.google.common.util.concurrent.ListeningExecutorService;  
 import com.google.common.util.concurrent.MoreExecutors;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class ListeningExecutorServiceExample {  
      @SuppressWarnings("unchecked")  
      public static void main(String a[]) {  
           ListeningExecutorService pool = MoreExecutors  
                     .listeningDecorator(Executors.newCachedThreadPool());  
           final ListenableFuture<String> future = pool.submit(new Callable() {  
                @Override  
                public String call() throws Exception {  
                     try {  
                          int a = 10 / 0;  
                     } catch (Exception e) {  
                          throw e;  
                     }  
                     return "done";  
                }  
           });  
           Futures.addCallback(future, new FutureCallback() {  
                @Override  
                public void onSuccess(Object object) {  
                     System.out.println("Success.");  
                }  
                public void onFailure(Throwable throwable) {  
                     System.out.println("Failure.");  
                }  
           });  
      }  
 }  


 Output  
 Failure.

So in this program ,the callback methods onSuccess and onFailure will be called once execution of the task is finished.In this case an arithmetic exception occurs which calls the callback method onFailure.You don't need to explicitly check the state of your ListenableFuture object ,as the registered callbacks will handle the states ,once the task is completed.

you need to download the guava jar ,here is the link http://www.java2s.com/Code/Jar/g/Downloadguavajar.htm

Enjoy programming

Sunday, 30 August 2015

Why POST method is non-idempotent and GET is idempotent ?




GET Method:-HTTP GET method is just for getting things from server.It is not supposed to change anything on server.So GET method is idempotent.It can be executed more than once without any side effects.
As you can see in below diagram,User request for a page and servlet sends back a response with a generated HTML page.You can call the same page again and again and server will return the response with no negative consequences that is called idempotent.





POST Method:-HTTP POST method is not idempotent i.e. the data submitted in the body of POST might be destined for transaction that can't be reversed.
As below diagram explains that when you submit your form ,POST method updates the data in database and servlet sends back an response.SO when you perform the submit action again,It will generate different response.





PUT,HEAD,DELETE methods are IDEMPOTENT just like GET method.

Enjoy Learning :)

Saturday, 29 August 2015

Finally block and Its Usage



What is finally block ?


finally block is either written after catch block or try block.finally blocks always executes when try block exits.Even if unexpected exception occurs in try block ,finally block is executed.It must be immediately followed by try or catch block.

Example:


/**  
  * @author Dixit  
  *   
  */  
 public class FinallyTest {  
      public static void main(String a[]) {  
           try {  
                System.out.println("Try block");  
           } catch (Exception e) {  
                System.out.println("catch block.");  
           } finally {  
                System.out.println("finally block.");  
           }  
      }  
 }  


Output  
 Try block  
 finally block.

Usage of finally block

finally block is mostly used to execute important code like closing db connection,closing file resources etc.

Also read Important finally interview questions

Enjoy Learning :)

Important finally interview questions


Important finally block questions which are commonly asked in interviews.

1) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.exit(0);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("finally block!!!");  
           }  

Output  
 Try block 

Reason:-the program will not execute finally block in this case because program is terminated using
System.exit(0) statement.

2) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.out.println(10 / 0);  
                System.exit(1);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("Finally block!!!");  
           }  

Output  
 Try block  
 java.lang.ArithmeticException: / by zero  
      at FinallyTest.main(FinallyTest.java:16)  
 Finally block!!!  

Reason:- An arithmetic exception occurred before executing statement System.exit(1).

3) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(tryCatchMethod());  
      }  
      private static int tryCatchMethod() {  
           try {  
                return 1;  
           } finally {  
                System.out.println("finally block");  
           }  
      }  
 }  

 Output  
 finally block  
 1  

Reason:-finally block runs before method returns 1 .

4) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                return 1;  
           } finally {  
                return 2;  
           }  
      }  
 }  

Output  
 2  

Reason:- return value in finally block ("2") overrides return value of try block ("1").

5) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                throw new NumberFormatException();  
           } finally {  
                return 2;  
           }  
      }  
 }  

 Output  
 2  

Reason:-Exception thrown by try block is overridden by return statement in finally block.That is why no exception is thrown.So Its bad practice to use return statements in finally block.

6)

 public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           int i = 0;  
        try {  
          i = 1;  
          return i;  
        } finally {  
          i = 2;  
          System.out.println("finally block.");  
        }  
      }  
 }  

Output  
 finally block.  
 1  

Reason:- when return i is executed i has a value 1 after that i is assigned new value in finally block to 2 and program prints "finally block.". but here 1 is returned because return statement is not executed again.

Enjoy programming :)

Top 10 Important shortcut keys for Windows


Shortcut keys mainly improve our work efficiency by speeding up the work.

Very basic and important shortcut key that everyone must know are:-

1) ALT + Tab :- It allows you to shuffle around your open application windows.It is very useful key to easily switch to other application windows.

2) CTRL + SHIFT +Del :-It opens the window option screen for Task Manager,locking computer,witiching user etc in latest version of windows.In Windows XP,It is meant for opening task manager.
CTRL + SHIFT + Esc is used to open Windows Task manager in Wndows XP and later.

3) SHIFT + Del :-It will delete the selected files permanently without moving them to recycle bin.

4) F2 :- Instead of right clicking on file and selecting rename option,F2 function key allows you to rename file instantly.

5) WIN + D :-It will display the desktop irrespective of how many opened application .
Similarly WIN + M will minimize all the current opened application and will display desktop. 

6) WIN + L :- Lock the computer and switch users (Windows XP and above only). 

7) WIN + R :-Opens the run command dialog box.

8) CTRL + C :- It will copy the highlighted text or selected file.If you want to cut highlighted text or selected file,press CTRL + X.

9) CTRL + V or SHIFT + Insert :- Both the shortcut keys will paste the highlighted text or selected file.

10) CTRL + Z or CTRL + Y :- CTRL + Z will undo the recent changes which you have done and CTRL + Y will redo the recent undo changes.
Enjoy Learning.