Friday, October 17, 2014

Command Design Pattern

One of my friends requested me to write a post on Command design pattern. I replied, your wish is my Command!

Command design pattern is a behavioral pattern and is also known as an action or transaction pattern.   It decouples the object that invokes the operation from the one having the knowledge to perform it. The invoker/requester and the receiver/doer are loosely coupled. Invoker object only knows how to issue/invoke the request (It doesn't know how the request will be carried out). Receiver (at the receiving end ;-) ) knows how to carry out a task/operation. Command objects connect these two pieces(invoker and receiver); let's refer this tri-chemistry as iCr.

                    Invoker --> {Command} --> Receiver

Intent (as put in Gang of four)
Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Command DP encapsulate a request as an object and pass it to an invoker, wherein the invoker does not knows how to service the request but uses the encapsulated command to perform an action. It takes an operation and its arguments and wraps them up in an object to be executed, logged, etc.
Invoker issues a request by calling execute method on the command. Then, concrete command invokes operation on its receiver to carry out a request. Below diagram shows sequence of events.


Ref : Gang of four design pattern


Implementation

Let's cover briefly the actors or components involved in this pattern.
  • Command: Defines an interface for executing an operation
  • Concrete Command: Binds a specific command to receiver
  • Invoker: Invokes or initiates command (stores concrete command object)
  • Receiver: Actual object which performs operation 
  • Client: Creates concrete command and sets corresponding receiver 
Clearly understanding role of all above is incredibly important. Instead of taking specific example and then illustrating this pattern, let's stick with above names itself. If the relationship among them is clear; visualizing a real example won't be difficult.


package command.pattern;

/**
 * Command or action class; usually just has single method 
 */
public interface Command {
 public void execute();
}


package command.pattern;

/**
 * Specific command implementation. There will be one class for each command 
 * like LightOnCommand, LightOffCommand, UndoCommand etc. 
 * 
 * Encapsulates the receiver.
 */
public class ConcreteCommand implements Command {
 private Receiver rec;

 public ConcreteCommand(Receiver rec) {
  this.rec = rec;
 }

 @Override
 public void execute() {
  rec.performTask();
 }

}


package command.pattern;

/**
 * Class responsible of doing the real work : turn on a light, cook food or
 * anything for you
 */
public class Receiver {
 public void performTask() {
  System.out.println("inside receiver");
  // do the assigned work
 }

}


package command.pattern;

/**
 * Takes instance of command and calls execute method to perform the work
 * Invoker doesn't know how the work will be done
 */
public class Invoker {
 private Command command;

 public void setCommand(Command com) {
  this.command = com;
 }

 public void performRequest() {
  command.execute();
 }

}


package command.pattern;

/**
 * Client class which connects the dots
 */
public class Client {
 public static void main(String[] args) {
  Command command = new ConcreteCommand(new Receiver());

  Invoker invoker = new Invoker();
  invoker.setCommand(command);
  invoker.performRequest();
 }
}

MVC framework, Struts uses command pattern to service HTTP requests. Struts provides a Servlet known as Action Servlet, which handles HTTP request and then invokes an application specific action. As a developer we don't need to bother about how things work under the hood. We just need to know how to map an HTTP request to a Struts action and how to implement that action. Similarly, Swing framework also uses this pattern to handle UI events on buttons and menu items. 


Undo/Redo support

As the intent of the pattern clearly explains, this pattern can be used for undo or redo operations as well. To support it, the Command will have to maintain the state . For undo, application will have to store the command that was executed last. This way application can store any amount of past actions and call those command in reverse direction to achieve multiple undo commands. Similarly, keep calling in forward direction to achieve redo. If list of all past actions/commands are stored, then it can be used for logging as well when the system crash.

                       --------------------------> redo
        { command1, command2, command3, .... ....commandn}
                     <------------------------------- undo
         

Below class shows a command which supports undo operation. The Command interface has to provide abstract undo() method along with execute().
                                                     


package command.pattern;

/**
 * Command to turn on light
 */
public class LightOnCommand implements Command {
 Light light;

 public LightOnCommand(Light light) {
  this.light = light;
 }

 @Override
 public void execute() {
  light.on();
 }

 @Override
 public void undo() {
  light.off();
 }
}

----
pattern..pattern...pattern !!!

Saturday, October 11, 2014

Check if a number is palindrome

A Palindrome number is a number which remains the same when its digits are reversed.

         if (number == reverse(number)){
            //number is palindrome
        } 

121, 1, 22 etc are palindrome numbers. In this post, I have discussed how to reverse a number. But, there could be an issue with the approach. Let's take below case:

In Java highest integer is, i.e. Integer.MAX_VALUE = 2147483647
Now, what if you try to reverse above number?

Reversed (i.e. 7463847412 ) number can't fit in an integer and hence it will overflow. One alternative is; store the value in a long and then reverse it. This approach will work but it's not a very cleaner and cooler way.
Let's figure out a different approach?

Algorithm

We can apply the more fundamental approach of comparing the first and last digits and if they are equal move to second and second last digits and so on. Keep doing it until the comparison fails or the number reduces to a single digit. This approach is followed to check if a string is palindrome. This approach doesn't have space overhead ( except two temporary variables to get left most and the right most digit). 

         number = 121   
         leftMostDigit = 1
         rightMostDigit = 1
         leftMostDigit == rightMostDigit
         so number = 2 

Implementation

Recursive implementation in Java. Each recursive call trims the right most and left most digit of the number.

          So 12321 will become 232 in the second call.

     /**  
       * Recursive method to check if a number is palindrome  
       *   
       * @param number  
       * @return true/false  
       */  
      public static boolean isPalindrome(int number){  
           System.out.println(" number is :"+ number);  
           if(number < 0){  
                isPalindrome(-number);  
           }  
           if(number < 10){  
                return true; //single letter number is always palindrome  
           }  
           int rightMostDigit = number % 10;  
           int leftMostDigit = number;  
           int factor = 1;  
           while(leftMostDigit >= 10 ){  
                leftMostDigit = leftMostDigit / 10;  
                factor = factor * 10;  
           }  
           if(leftMostDigit != rightMostDigit){  
                return false;                 
           }  
           number = number % factor; //remove left most number  
           number = number / 10; // remove right most number  
           return isPalindrome(number);  
      }  

--
keep coding !!!

Sunday, September 21, 2014

Algorithm: Reverse an integer

Problem: Reverse an integer
17 reverses to 71
9 reverses to 9
-2367 reverses to -7632
*** space overhead NOT allowed


Solution

This problem can be easily solved if space overhead is allowed. You can convert the integer into a string and then reverse the string and parse back string into an integer. But what makes this problem interesting is if you have to do it without any space overhead (except that of the result). Below is the Java implementation of the same. 


     /**  
       * Reverse a integer (handles negatives also)  
       *   
       * @param num  
       * @return  
       */  
      public static int reverseNum(int num) {  
           boolean negative = false;  
           if (num < 0) {  
                num = -num;  
                negative = true;  
           }  
           int reverse = 0;  
           while (num > 0) {  
                reverse = reverse * 10 + num % 10;  
                num /= 10;  
           }  
           if (negative) {  
                reverse = -reverse;  
           }  
           return reverse;  
      }  

Note: What if number overflows? 
If the number overflows the reversed number will not fit in the integer data type.
One of the possible ways would be to store reversedNum in long and then check if it's value is out of integer range and then do something like below:
if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) {
        return 0;
 } else {
        return (int) reverse;
 }
So refactor your code to make sure that overflow is taken into consideration. There are other ways to check if number overflows (like positive number will become negative). But, I think the above approach is much cleaner.

Checking if the number is a palindrome
This method can be used to check if a number is a palindrome.
if (reverse(num) == num ){
  //num is palindrome
}

--
keep coding !!!

Sunday, September 14, 2014

Binary Search on a sorted file in Java

Binary search on a sorted array/list is quite trivial. But at times, you might get a file having sorted items and asked to find if a given item exists in it or not?

If the number of elements in the file is less, you can easily stream file in an array and then apply binary search. But what if the size of the file is huge or you don't have enough available memory to read the full content in an array. Can we apply binary search directly on file? YES!!!

Random Access File

Java I/O API provides a class named as RandomAccessFile. It has a different behavior than other InputStream or OutputStream classes. RandomAccesFile allows you to move forward and backward within the file using seek() method. It also provides length() method to give the maximum size of the file. And you can open a file either in read mode or read/write mode by passing "r" or "rw" in the constructor. 

Write sorted integers to a file:
 RandomAccessFile file = 
               new RandomAccessFile("sortedFile.txt", "rw");
for (int i = 0; i < 10; i++) {
file.writeInt(i * i);
}
file.close(); 

Java Implementation 

Below binary search implementation on a file.


 /**
  * Binary search
  * 
  * @param fileName
  *            input file name
  * @param num
  *            target input to be searched
  * @return true if search is successful
  */
 public boolean binarySearch(String fileName, int num) {
  Objects.requireNonNull(fileName, "valid filename is required !");

  // printFile(fileName);
  try {
   RandomAccessFile raf = new RandomAccessFile(fileName, "r");
   int first = raf.readInt();
   if (num == first)
    return true;

   int count = (int) (raf.length() >> 2);
   int midIndex, midValue, endIndex = count - 1, startIndex = 0;

   while (startIndex <= endIndex) {
    midIndex = (endIndex + startIndex) >> 1;

    // move file pointer to midIndex
    raf.seek(midIndex * 4);

    midValue = raf.readInt();
    if (midValue == num) {
     return true;
    } else {
     if (midValue > num) {
      endIndex = midIndex - 1;
     } else {
      startIndex = midIndex + 1;
     }
    }
   }
   raf.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return false;
 }

--

keep coding !!!

Monday, September 8, 2014

Bit Vector

The bit vector is also referred to as bit-array or bit-set. As the name suggests, it's array of bits. Every modern programming language supports primitive or basic data types like byte, integer, short etc which are inherently array of bits only. So, is bit-array different? 

A byte is composed of 8-bits. Literally, byte data type is also a bit-array of 8 bits or 1 byte.  Integer data type of 4 bytes is a bit-array of 32 bits and so on. This is where the similarity stops and life of bit-array begins. 

To understand it further let's take an example. Assume that you want to represent a set of integers in the range of 0 and 999 (both are inclusive). An option which you have as a programmer is; store these integers in an array of length 1000 or a list which can grow up to 1000. Remember, it's a set, so you are going to store only unique numbers in the range. 

//Java snippet
int[] set = new int[1000];
set[i] = num

What is the memory requirement of above?
Each integer takes 4 bytes. So total memory requirement for 1000 integers is 4KB (=4*1000 byte).  

can we improve? 
If the requirement says that not all numbers in the range might be present in the set, we can use ArrayList instead of an array. So this will improve a bit, as the numbers which are not in the set will not occupy any memory. This helps to an extent but worst-case memory requirement is still 4KB. 

can we improve?
As long as you going to store each element of the set in an integer, space overhead is going to remain the same.

Bit-Array

A bit can only take two values i.e. 0 or 1.  It can be used to denote the presence or absence of an item. So as discussed above, a byte is an array of 8 bits. This means these 8 bits can be used to represent presence/absence of an item in the set. Recall that in an integer array, the index is used to get element stored at that location. Similarly, in bit-set, bit at a position can be used to represent the presence of a number.

So as shown in the above figure, we can represent a set of integers in the range of 0 and 7, can be represented by just 1 byte ( or 8 bits). If the number is present make bit at the corresponding bit as 1. 

So below two operations can be performed on bit-set.
  1. Setting an integer in the array
  2. Testing if an integer exists in the array/set

Implementing Bit-vector

Now, let's return to our initial problem of storing integers in the range of 0 and 999. 

Number of bits required = 1000
Number of bytes required = 1000/8 = 125
So 1000 integers can be represented in 125 bytes.

Below is the Java implementation:

/**
 * Bit-vector to store integers
 * 
 * @author Siddheshwar
 * 
 */
public class BitArray {
 private byte[] set;

 public BitArray(int length) {
  int arraysize = length >> 3;

  // if length is not multiple of 8
  if (length % 8 != 0) {
   arraysize++;
  }
  this.set = new byte[arraysize];
 }

 /**
  * Set given number in the bit-array i.e. make corresponding bit as 1
  * 
  * @param number
  */
 public void storeNumber(int number) {
  if (number > (set.length << 3) || number < 0) {
   throw new IllegalArgumentException("number out of range");
  }

  int arrayIndex = this.getArrayIndex(number);
  int bitIndex = this.getBitIndex(number);

  // shift 1 to the bit index
  int pos = 1 << bitIndex;

  // so bit at position needs to be made 1
  this.set[arrayIndex] = (byte) (this.set[arrayIndex] | pos);
 }

 /**
  * Check if the number exists in the array if the corresponding bit is 1
  * then number exists
  * 
  * @param number
  */
 public boolean numberExists(int number) {
  if (number > (set.length << 3) || number < 0) {
   throw new IllegalArgumentException("number out of range");
  }

  int arrayIndex = this.getArrayIndex(number);
  int bitIndex = this.getBitIndex(number);

  // shift 1 to the bit index
  int pos = 1 << bitIndex;

  // check bit at position is 0 or 1
  return (this.set[arrayIndex] & pos) > 0 ? true : false;
 }

 private int getArrayIndex(int number) {
  return number >> 3; // divide by 8
 }

 private int getBitIndex(int number) {
  return number % (1 << 3); // % 8
 }

 private void printSet() {
  System.out.println("\n array content :");
  for (int i = 0; i < set.length; i++)
   System.out.print(Integer.toBinaryString(this.set[i]));
 }

 //test method
 public static void main(String[] args) {
  BitArray array = new BitArray(1000);
  System.out.println("length of array :" + array.set.length);

  int num1 = 17;
  array.storeNumber(num1);

  int num2 = 171;
  array.storeNumber(num2);

  int num3 = 400;
  array.storeNumber(num3);

  System.out.println("val " + num1 + " exists ? "
    + array.numberExists(num1));
  System.out.println("val " + num2 + " exists ? "
    + array.numberExists(num2));
  System.out.println("val " + num3 + " exists ? "
    + array.numberExists(num3));
  System.out.println("val " + 500 + " exists ? "
    + array.numberExists(500));

  for (int i = 0; i < 1000; i = i + 2)
   array.storeNumber(i);

  array.printSet();

  /*
   * for(int i = 0; i< 1000; i++) System.out.println(array.get(i));
   */
 }
}

Output:
length of array :125
val 17 exists ? true
val 171 exists ? true
val 400 exists ? true
val 500 exists ? false

 array content :
10101011010101101011110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110111011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101101010110101011010101


---
keep coding !!!