Tuesday 9 September 2014

Program to find shortest distance to particular value in a matrix

Given a matrix of -1's and 0's, display a matrix which contains minimum distance to reach nearest 0 from that particular position.
Example:
Input1: 
-1,0,-1
-1,-1,-1
-1,-1,-1
Output: 
1,0,1
2,1,2
3,2,3

Input2: 
-1,0,-1
-1,-1,-1
-1,0,-1
Output:
1,0,1
2,1,2
1,0,1

Algorithm:
1. Figure out the all positions in matrix having zero and cache them.
2. Calculate the distance from each position to the cached zero positions by summing absolute distance of x and y co-ordinates.
3. Put the minimum value in the result matrix.


package com.prasune.coding;

import java.util.ArrayList;
import java.util.List;

public class ShortestDistance {

      public static void main(String[] args) {
            int matrix[][] = {
                                  {-1,0,-1},
                                  {-1,-1,-1},
                                  {-1,0,-1}
                                 };
            printAsMatrix(matrix);
            printDistanceToZero(matrix);
      }

      private static void printDistanceToZero(int[][] matrix) {
            int[][] resultMatrix = new int[matrix.length][matrix.length];
            List<Position> zeroPositions = new ArrayList<Position>();
           
            for (int i = 0; i < matrix.length; i++) {
                  for (int j = 0; j < matrix[i].length; j++) {
                        if(matrix[i][j] == 0){
                              zeroPositions.add(new Position(i,j));
                        }                      
                  }
            }
           
            for (int i = 0; i < matrix.length; i++) {
                  for (int j = 0; j < matrix[i].length; j++) {
                        if(matrix[i][j] == 0){
                              resultMatrix[i][j] = 0;
                        } else{
                              int minValue = Integer.MAX_VALUE;
                              for (Position position : zeroPositions) {
                                    int tempMinValue = Math.abs(i - position.getRowNum()) +
                                                               Math.abs(j - position.getColNum());
                                    if(tempMinValue < minValue){
                                          minValue = tempMinValue;
                                    }
                              }
                              resultMatrix[i][j] = minValue;
                        }                                        
                  }
            }
            printAsMatrix(resultMatrix);
      }

      private static void printAsMatrix(int[][] matrix) {
            for (int i = 0; i < matrix.length; i++) {
                  for (int j = 0; j < matrix[i].length; j++) {
                        System.out.print(matrix[i][j]);
                        if(j < matrix[i].length-1){
                              System.out.print(",");
                        }                      
                  }
                  System.out.println();
            }
      }
}

Position.java

package com.prasune.coding;

public class Position {

      private int rowNum;
      private int colNum;
     
      public Position(int rowNum, int colNum) {
            this.rowNum = rowNum;
            this.colNum = colNum;
      }
      public int getRowNum() {
            return rowNum;
      }
      public void setRowNum(int rowNum) {
            this.rowNum = rowNum;
      }
      public int getColNum() {
            return colNum;
      }
      public void setColNum(int colNum) {
            this.colNum = colNum;
      }
}




Sunday 7 September 2014

Add two large numbers that cannot be stored in numeric data types

You are given two numbers as String which are so large that it cannot be stored in any of the numeric data types. You need to return the sum of these numbers as String.

"it cannot be stored in any of the numeric data types" means it includes Long, BigDecimal etc.. Assume around 1000 digits in the number

package com.prasune.coding;

import java.util.Stack;

public class AddBigNumbers {

      public static void main(String[] args) {
            String number1 = "123456789129";
            String number2 = "345343";
            System.out.println(add(number1, number2));
      }

      public static String add(String number1, String number2){
            String result = "";
            Stack<Integer> n1 = new Stack<Integer>();
            Stack<Integer> n2 = new Stack<Integer>();
            Stack<Integer> sum = new Stack<Integer>();
            int carryForwardValue = 0;
            for (int i = 0; i < number1.length(); i++) {
                  n1.push(Integer.parseInt("" + number1.charAt(i)));
            }
            for (int i = 0; i < number2.length(); i++) {
                  n2.push(Integer.parseInt("" + number2.charAt(i)));
            }
            while(!n1.empty() || !n2.empty()){
                  int digit1 = 0;
                  int digit2 = 0;
                  if(!n1.empty()){
                        digit1 = n1.pop();
                  }
                  if(!n2.empty()){
                        digit2 = n2.pop();
                  }                
                  int sumOfNumbers = digit1 + digit2 + carryForwardValue;
                  sum.push(sumOfNumbers % 10);
                  carryForwardValue = sumOfNumbers/10;
            }
            while(!sum.empty()){
                  result = result + sum.pop();
            }
            return result;
      }
}



Friday 5 September 2014

Program to reverse a given sentence in java

Write a program to reverse a sentence in Java

For example if you have a sentence "Quick brown fox jumped over a lazy dog",
your output should be "dog lazy a over jumped fox brown Quick"


package com.prasune.coding;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseSentence {

      public static void main(String[] args) {
            System.out.println(getReverseString("Quick brown fox jumped over a lazy dog"));
      }

      public static String getReverseString(String str){
        StringTokenizer tokenizer = new StringTokenizer(str);
        Stack<String> stack = new Stack<String>();
        String reversedString = "";
        while(tokenizer.hasMoreTokens()){
          stack.push(tokenizer.nextToken());
        }
        while(!stack.empty()){
              reversedString = reversedString + stack.pop() + " ";
        }
        return reversedString.trim();
      }
}





Friday 25 July 2014

How to e-File your Income Tax return

Filing of income tax return is now made a lot easier with the new UI form for e-filing the returns which was introduced last year (2012-2013).

For filing your income tax return go to the government of India website:
 https://incometaxindiaefiling.gov.in/e-Filing/UserLogin/LoginHome.html

Register your PAN number at this site if you have not done already and login to this site.


Form 26AS (Tax Credit)

Before beginning with filing of your tax return, please have a look at your Form 26AS which shows the tax credited against your PAN number. This will show the tax credit done by your employer as well as the tax credited by other entities like your savings bank. Click on 'View Form 26AS (Tax Credit) and follow the instructions for viewing your Form 26AS. Assessment year needs to be given as next year of the financial year (for e.g 2013-2014 financial year has 2014-2015 as assessment year).

If you are earning an income of more than 10,000 in your savings account via FD or interest, then the bank will deduct 10% of this amount as TDS and pay to the Income Tax Department. This data will also be seen in your form 26AS. The additional income that is shown by the bank needs to be added to your taxable income and the excess tax if any need to be paid as self assessment tax. How to e-pay the self assesment tax will be discussed later.

e-File ITR

If you do not have any pending tax to be paid, then you can go forward to file the Income Tax return. Click on 'Quick e-File ITR' link for starting this procedure.
Select ITR-1 and assessment year as the year next to the financial year. You can chose to pre-fill your personal details from the PAN Database or from previously filled returns. Keep saving your form while filling the details for filing return.

In the 'Income Details' section, for 'Income from salary', the form 16 component of 'Income chargeable under the head 'Salaries'' needs to be filled in.
If you have an additional income from FD or any other sources, then that needs to be mentioned against 'Income from other sources'
The deduction under 80C/80D etc needs to be filled in from form 16.

The 'Tax Details' could be already pre-filled with the income as well as tax details as seen in Form 26AS. Please cross-check if both are in sync.

Check the 'Taxes Paid And Verification' section. There should not be any tax pending to be paid. If there is no tax balance, then you can go ahead and submit your return.
If there is then pay the additional tax as self assessment tax and fill it in the 'Tax Details section' under 'Sch IT - Details of advance Tax and Self Assessment Tax Payments' section. The necessary details will be available once the e-Tax payment is confirmed. Once it is confirmed that there is no tax pending to be paid, you can submit your return.

Once the IT return is filed, you will get ITR-V for download, the password of the same will be your pan number in small letters followed by your date of birth in ddmmyyyy format. Verify the income, tax paid and tax balance mentioned in the ITR-V. This needs to signed and sent via post to the address mentioned of income tax department.

e-Pay self assessment tax

Click on the 'E-Pay Tax' link marked in the links if you have additional tax that needs to be paid.
Select the option - CHALLAN NO./ITNS 280 (payment of Income tax & Corporation Tax)

In the form, select the following options:
(0021)INCOME-TAX (OTHER THAN COMPANIES)
(300)SELF ASSESSMENT TAX
And fill in your details including PAN number and assessment year. Assessment year needs to be given as next year of the financial year (for e.g 2013-2014 financial year has 2014-2015 as assessment year). Mention the bank from which you wish to pay the self assessment tax. On confirmation of the payment the BSR code, challan number and details of the tax payment will be displayed. Save the details and fill it in the 'Tax Details section' under 'Sch IT - Details of advance Tax and Self Assessment Tax Payments' section as mentioned in e-file ITR section.

Sunday 8 June 2014

Examples of EJB 3.1 TimerService - Programmatic Timers

A programmatic timer is typically required when there is a user interface that controls the scheduling activity.
User would be able to start or stop a scheduler which do certain processing using the specified timer schedule. Here is a simple example of a programmatic EJB Timer.

In this example, it is assumed that the application have a SessionBean facade(s) which have all the business methods. A SessionBean facade is required for making use of the container managed persistence context in the business methods. The timer just invokes the relevant business method based on the timer schedule expiration.

package com.prasune.ejb.timer;

import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.ScheduleExpression;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

import com.prasune.ejb.persistence.JPASessionFacade;

@Stateless(name = "ProgramaticTimer", mappedName = "ProgramaticTimer")
public class ProgramaticTimerBean implements ProgramaticTimer {
   
    @Resource
    TimerService timerService;
   
    @EJB
    private JPASessionFacade jpaSessionFacade;

    public ProgramaticTimerBean() {
    }

    @Timeout
    public void doProcess(Timer timer) {
        System.out.println("Programatic Timer got invoked at " + new Date());
        jpaSessionFacade.dmlOperation();
    }
   
    public void startScheduler(){
        ScheduleExpression scheduleExpression = new ScheduleExpression();
        scheduleExpression.hour("*").minute("*").second("*/5");
        timerService.createCalendarTimer(scheduleExpression, new TimerConfig("TestTimer", true));
        System.out.println("Programatic Timer got created succesfully");
    }
   
    public void stopScheduler(String schedulerId) {
        if (timerService.getTimers() != null) {
            for (Timer timer : timerService.getTimers()) {
                if (timer.getInfo().equals(schedulerId)) {
                    timer.cancel();
                    System.out.println("Programatic Timer got stopped succesfully");
                }
            }
        }
    }
}


startScheduler() method creates a timer using the calendar based ejb ScheduleExpression.
The ScheduleExpression is very similar to chrone job schedule expression. Detailed usage of the ScheduleExpression for creating a timer can be found at Understanding EJB Timer Service 3.1.
In the example, we are creating a timer schedule to be executed every 5 seconds from now.

TimerConfig: There is an optional TimerConfig that can be passed while creating the calendar based timer. In the TimerConfig, we can specify an info like an Id using which we can identify the Timer. The Timer needs to be identified for stopping it as and when the user requires to do the same.The second parameter of the TimerConfig decides whether the Timer Schedule needs to be persisted or not. This is by default true and it means that the schedule of the timer is persisted and is not specific to JVM. Hence, it can survive a server crash.

@Resource annotation is used by the JEE server to inject the TimerService to the EJB.

@Timeout annotation is used to mark the method to be executed on timer schedule expiration. A programmatic Timer can have only one method with this annotation per EJB. The doProcess() method executes the relevant business method specified from the SessionBean facade.

@EJB annotation is used by the JEE server for injecting the SessionBean facade for calling the relevant business method.

stopScheduler() method fetches the Timers registered with TimerService and uses the TimerConfig info to identify the relevant timer and stops it.


ProgramaticTimer is the Local and Remote interface of the EJB. Although it is not mandatory to have a separate interface and the EJB can be annotated with Local/Remote annotations, it is better to program to interface. This will help while multiple applications are involved as the integrator needs to be given only the interface. 

package com.prasune.ejb.timer;

import javax.ejb.Local;
import javax.ejb.Remote;

@Local
@Remote
public interface ProgramaticTimer {
    public void startScheduler();
    public void stopScheduler(String schedulerId);
}


ProgramaticTimerRemoteClient is a sample remote client for invoking the timer application to see if it is working fine. The example client uses Weblogic server initial context. The ProgramaticTimerBean APIs can be called for starting/stopping the scheduler and to verify whether it is working fine.

package com.prasune.ejb.timer.client;

import com.prasune.ejb.timer.ProgramaticTimer;

import java.util.Hashtable;

import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ProgramaticTimerRemoteClient {
    public static void main(String[] args) {
        try {
            final Context context = getInitialContext();
            ProgramaticTimer programaticTimer =
                (ProgramaticTimer) context.lookup("ProgramaticTimer#com.prasune.ejb.timer.ProgramaticTimer");
            programaticTimer.startScheduler();
            //programaticTimer.stopScheduler("TestTimer");
            System.out.println("Invoked Timer");
        } catch (CommunicationException ex) {
            System.out.println(ex.getClass().getName());
            System.out.println(ex.getRootCause().getLocalizedMessage());
            System.out.println("\n*** A CommunicationException was raised.  This typically\n*** occurs when the target WebLogic server is not running.\n");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static Context getInitialContext() throws NamingException {
        Hashtable env = new Hashtable();
        // WebLogic Server 10.x/12.x connection details
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
        return new InitialContext(env);
    }
}


Packaging and Deployment

Packaging and deployment of an EJB 3.1 Timer is very simple. The class file needs to be in a jar file with the correct directory structure of the package and the jar file can be directly deployed on any JEE server supporting EJB 3.1. The vendor specific ejb-jar.xml are optional and annotations are sufficient for the JEE server to identify the class as EJB Timer