Wednesday, 9 September 2015

How to use superscript in HighChart labels

This is how you can use superscript in HighChart labels using useHTML property :

(you can run and edit below code here  : http://jsfiddle.net/lahoti32/j0ue1naf/ )

$(function () {
    $('#container').highcharts({
chart: {
            type: 'column'
        },
        credits : {
            enabled : false
        },
        title: {
            text: 'Chart Title<sup>1</sup>',
            useHTML : true,
        },
        xAxis: {
categories: [ 'label1','label2','label3<sup>4</sup>','label4'],
            title:{
                enabled: false
            },
            labels: {
                useHTML : true,
                title: {
                    enabled: false
                }         
            },
        },
        yAxis: {
            title: {
                enabled: false
            },
            labels: {
                useHTML : true,
                formatter:function(){
                    if(this.value != 10){
                        return this.value;
                    }else{
                        return this.value + '<sup> 2</sup>';
                    }
                }
            }
        },
        legend: {
            useHTML : true,
            borderWidth: 0,
            labelFormatter:function(){
                if(this.name != 'legend1'){
                    return this.name;
                }else{
                    return this.name + '<sup> 5</sup>';
                }
            }
        },
        plotOptions: {
            column: {
                dataLabels: {
                    enabled: true,
                    useHTML : true,
                    y:-1,
                    formatter:function(){
                        if(this.y != 0){
                            if(this.y > 8 && this.y < 10){
                                return this.y + '<sup> 3</sup>';
                            }else{
                                return this.y;
                            }

                        }else{
                            return null;
                        }
                    }
                }
            }
        },
        series: [{ 
            data: [{ 
                y: 14.913
            }, { 
                y: 8.281
            }, { 
                y: 3.592
            }, { 
                y: 3.017
            }], 
            showInLegend: false,
        },{
            name: 'legend1',
            color: 'rgb(14,178,89)'      
        },{
            name: 'legend2',
            color: 'rgb(100,100,9)'      
        }]
    });
});

Sunday, 12 July 2015

fibonacci series in java

Fibonacci series implementation in java is frequently asked question in interview at fresher level. Moreover, it is a very famous example to show how to use recursive function in java.


public class Fibonacci {

    public static void main(String[] args){
        fibonacci(15);
    }
    
    /**
     * This method is used to print fibonacci series
     * @param n is total number of elements
     */
    private static void fibonacci(int n){
        for(int i = 0 ; i < n; i ++){
            System.out.print(fib(i)+", ");
        }
    }
    /**
     * This method is used recursively to find fibonacci
     * element at nth index. 
     * @param n is index
     * @return element
     */
    private static int fib(int n){
        if(n < 2)
            return n;
        return fib(n-1) + fib(n-2);
    }
}

Output : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 

Tuesday, 9 June 2015

Sorting Algorithm : Bubble Sort

Why it is called bubble sort ?

Bubble Sort is nothing but a comparison algorithm where - 
- At the end of first iteration, largest element in the array get placed at last index
- At the end of second iteration, second largest element in the array get placed at second last index and so on...
This way large elements are moving towards the last indexes and hence small elements are moving towards the starting indexes which is also termed as smaller elements "bubble" to the top of the list that is why it is called bubble sort.

Step-by-step example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required.
First Pass:
5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) \to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )

Algorithm In Java


package com.test.algorithm.sort;
/*
 *Bubble Sort is nothing but a comparison algorithm where - 
 *- At the end of first iteration, largest element in the array get placed at last index
 *- At the end of second iteration, second largest element in the array get placed at second last index and so on...
 *This way large elements are moving towards the last indexes and hence small elements are moving towards the starting indexes 
 *which is also termed as smaller elements "bubble" to the top of the list that is why it is called bubble sort.
 */

public class BubbleSort {

    public static void main(String[] args){
        int[] array = new int[]{5, 1, 12, -5, 16};
        BubbleSort.sort(array);
    }
    
    private static void sort(int[] array){
        int count = 0;
        for(int i = array.length ; i > 0 ; i --, count++){
            for(int j = 0 ; j < array.length-1 ; j++, count++){
                if(array[j] > array[j+1]){
                    swapNumbers(j, j+1, array);
                }
            }
        }
        printNumbers(array, count);
    }
    
    private static void swapNumbers(int i, int j, int[] array) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    
    private static void printNumbers(int[] array, int count) {
        System.out.print("Sorted Array : {");
        for(int i : array){
            System.out.print(i + " ");
        }
        System.out.print("}, n : " + array.length + ", comparisons : " + count);
    }
}

Output : Sorted Array : {-5 1 5 12 16 }, n : 5, comparisons : 25

Time Complexity for worst case is O(n2). Algorithm can be further improved :

private static void sort(int[] array){
        int count = 0;
        for(int i = array.length ; i > 0 ; i --, count++){
            for(int j = 0 ; j < i-1 ; j++, count++){
                if(array[j] > array[j+1]){
                    swapNumbers(j, j+1, array);
                }
            }
        }
        printNumbers(array, count);
    }

Output :Sorted Array : {-5 1 5 12 16 }, n : 5, comparisons : 15

Friday, 1 May 2015

Stack Implementation Using Priority Queue

Stacks may be modeled as particular kinds of priority queues. In a stack, the priority of each inserted element is monotonically increasing; thus, the last element inserted is always the first retrieved.
Stack Implementation : 

import java.util.NoSuchElementException;
import java.util.PriorityQueue;


public class StackImplementationUsingPQ {

    private PriorityQueue pq = new PriorityQueue();
    private int counter = 0;
    
    public void push(String s){
        Element e = new Element(s, counter++);
        pq.add(e);
    }
    
    public String pop(){
        Element e = null;
        try{
            e = pq.remove();
            counter--;
        }catch(NoSuchElementException ex){
            return "'Stack is Empty'";
        }
        return e.toString();
    }
    
    public static void main(String[] args){
        StackImplementationUsingPQ stack = new StackImplementationUsingPQ();
        stack.push("Banana");
        stack.push("Mango");
        stack.push("Apple");
        System.out.println(stack.pop());
        stack.push("Orange");
        stack.push("Pinapple");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
    
}
class Element implements Comparable{
    
    private Integer priority;
    private String value;
    
    Element(String value, Integer priority){
        this.value = value;
        this.priority = priority;
    }
    
    
    public Integer getPriority() {
        return priority;
    }
    public void setPriority(Integer priority) {
        this.priority = priority;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int compareTo(Element o) {
        return o.getPriority().compareTo(this.getPriority());
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("value : ");
        sb.append(getValue());
        sb.append(", ");
        sb.append("priority : ");
        sb.append(getPriority());
        return sb.toString();
    }

Output:

value : Apple, priority : 2
value : Pinapple, priority : 3
value : Orange, priority : 2
value : Mango, priority : 1
value : Banana, priority : 0
'Stack is Empty'

Monday, 6 April 2015

Elevator Implementation in Java

Implementation of Elevator/ Lift has been asked in many interviews. I have tried to implement it using muti-threading and TreeSet. TreeSet is used to store incoming request. It is a good choice here as it removes the duplicate requests and implements NavigableSet which provide you methods such as floor and ceiling.

Elevator in this program implements following features -
  • If elevator is going up or down, it checks for nearest floor request to process first in that direction. 
  • If there is no request to process, it waits at last processed floor.
  • If a new request comes while elevator is processing a request. It process the new request first if it is nearest than the processing floor in same direction.




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;

public class MyLift {

    public static void main(String[] args) {
        System.out.println("Welcome to MyLift");
        // RequestListenerThread to read requested floor and add to Set
        Thread requestListenerThread = new Thread(new RequestListener(),
                "RequestListenerThread");
        // RequestProcessorThread to read Set and process requested floor
        Thread requestProcessorThread = new Thread(new RequestProcessor(),
                "RequestProcessorThread");
        
        Elevator.getInstance().setRequestProcessorThread(requestProcessorThread);
        
        requestListenerThread.start();
        requestProcessorThread.start();
        
        
    }
}

class Elevator {
    
    private static Elevator elevator = null;
    
    private TreeSet requestSet = new TreeSet();
    
    private int currentFloor = 0;

    private Direction direction = Direction.UP;

    private Elevator() {};
    
    private Thread requestProcessorThread;

    /**
     * @return singleton instance
     */

    static Elevator getInstance() {
        if (elevator == null) {
            elevator = new Elevator();
        }
        return elevator;
    }

    /**
     * Add request to Set
     * 
     * @param floor
     */

    public synchronized void addFloor(int f) {
        requestSet.add(f);
        
        if(requestProcessorThread.getState() == Thread.State.WAITING){
            // Notify processor thread that a new request has come if it is waiting
            notify();
        }else{
            // Interrupt Processor thread to check if new request should be processed before current request or not. 
            requestProcessorThread.interrupt();
        }
        
    }

    /**
     * @return next request to process based on elevator current floor and direction
     */

    public synchronized int nextFloor() {

        Integer floor = null;

        if (direction == Direction.UP) {
            if (requestSet.ceiling(currentFloor) != null) {
                floor = requestSet.ceiling(currentFloor);
            } else {
                floor = requestSet.floor(currentFloor);
            }
        } else {
            if (requestSet.floor(currentFloor) != null) {
                floor = requestSet.floor(currentFloor);
            } else {
                floor = requestSet.ceiling(currentFloor);
            }
        }
        if (floor == null) {
            try {
                System.out.println("Waiting at Floor :" + getCurrentFloor());
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            // Remove the request from Set as it is the request in Progress.
            requestSet.remove(floor);
        }
        return (floor == null) ? -1 : floor;
    }

    public int getCurrentFloor() {
        return currentFloor;
    }
    
    /**
     * Set current floor and direction based on requested floor
     * 
     * @param currentFloor
     * @throws InterruptedException 
     */

    public void setCurrentFloor(int currentFloor) throws InterruptedException {
        if (this.currentFloor > currentFloor) {
            setDirection(Direction.DOWN);
        } else {
            setDirection(Direction.UP);
        }
        this.currentFloor = currentFloor;
        
        System.out.println("Floor : " + currentFloor);
        
        Thread.sleep(3000);
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public Thread getRequestProcessorThread() {
        return requestProcessorThread;
    }

    public void setRequestProcessorThread(Thread requestProcessorThread) {
        this.requestProcessorThread = requestProcessorThread;
    }

    public TreeSet getRequestSet() {
        return requestSet;
    }

    public void setRequestSet(TreeSet requestSet) {
        this.requestSet = requestSet;
    }
    
}

class RequestProcessor implements Runnable {

    @Override
    public void run() {
        while (true) {
            Elevator elevator = Elevator.getInstance();
            int floor = elevator.nextFloor();
            int currentFloor = elevator.getCurrentFloor();
            try{
                if (floor >= 0) {
                    if (currentFloor > floor) {
                        while (currentFloor > floor) {
                            elevator.setCurrentFloor(--currentFloor);
                        }
                    } else {
                        while (currentFloor < floor) {
                            elevator.setCurrentFloor(++currentFloor);
                        }
                    }
                    System.out.println("Welcome to Floor : " + elevator.getCurrentFloor());
                }
                
            }catch(InterruptedException e){
                // If a new request has interrupted a current request processing then check -
                // -if the current request is already processed
                // -otherwise add it back in request Set
                if(elevator.getCurrentFloor() != floor){
                    elevator.getRequestSet().add(floor);
                }
            }
        }
    }
}

class RequestListener implements Runnable {

    @Override
    public void run() {

        while (true) {
            String floorNumberStr = null;
            try {
                // Read input from console
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                floorNumberStr = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (isValidFloorNumber(floorNumberStr)) {
                System.out.println("User Pressed : " + floorNumberStr);
                Elevator elevator = Elevator.getInstance();
                elevator.addFloor(Integer.parseInt(floorNumberStr));
            } else {
                System.out.println("Floor Request Invalid : " + floorNumberStr);
            }
        }
    }

    /**
     * This method is used to define maximum floors this elevator can process.
     * @param s - requested floor
     * @return true if requested floor is integer and upto two digits. (max floor = 99)
     */

    private boolean isValidFloorNumber(String s) {
        return (s != null) && s.matches("\\d{1,2}");
    }

}

enum Direction {
    UP, DOWN
}