Sunday, 19 August 2018

How to use multiple pathVariable in spring mvc using map


@RequestMapping("/hello/{userName}/{country}")
public methodName(@PathVariable Map<String,String> map){
    String userName = map.get("userName");
    String country = map.get("country");
}

and below code in dispatcher-servelet:

<mvc:annotation-driven/>

find max sub array program

Program1: find sum of maxSubArray

 public int maxSubArray(final int[] A) {
     int largestSum = Integer.MIN_VALUE;
        int tempSum = 0;
        for(int i=0;i<A.length;i++) {
            if(tempSum+A[i]<A[i]) {
                tempSum = A[i];
            }else {
                tempSum = tempSum+A[i];
            }
           
            if((tempSum>Integer.MIN_VALUE && tempSum>largestSum) || tempSum>0) {
                 if(largestSum<tempSum){
                    largestSum = tempSum;
                
                    }
            }else {
                tempSum=0;
            }
        }
        return largestSum;
    }


intput:{-2,1,-3,-4,-1,-2,-1,-7,-5,-4}

output: 1


innput:{-160,-20,-10}
output -10

input: -160,-20,-10,1,2
output: 3



Program2: find sum of maxSubArray with start and end index

public static void findMaxSumSubArray(int[] arr) {
        int largestSum = Integer.MIN_VALUE;
        int tempSum = 0;
        int startIndex = 0;
        int endIndex = 0;
        int s = 0;
        for(int i=0;i<arr.length;i++) {
            if(tempSum+arr[i]<arr[i]) {
                tempSum = arr[i];
            }else {
                tempSum = tempSum+arr[i];
            }
           
            if((tempSum>Integer.MIN_VALUE && tempSum>largestSum) || tempSum>0) {
                 if(largestSum<tempSum){
                     endIndex = i;
                     startIndex = s;
                    largestSum = tempSum;
               
                    }
            }else {
                s = i+1;
                tempSum=0;
            }
        }
        System.out.println("index start::"+startIndex +" and end: "+endIndex);
        System.out.println("sum::"+largestSum);
    }


Saturday, 18 August 2018

Find Noble Integer Program

Question: Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p
If such an integer is found return 1 else return -1.

Solution:
static int checkNobleInteger(int[] arr) {
        for(int i=0;i<arr.length;i++) {
           
            int count = 0;
            for(int j=0;j<arr.length;j++) {
               
                if(arr.length-j+count<arr[i]) {
                    break;
                }
               
                if(arr[j]>arr[i]) {
                    count++;
                }
            }
            if(arr[i]==count) {
                return 1;
            }
        }
        return -1;
    }

input: {4, 3, 5, 6, 7, 8}
output: 1


input: {6, 3, 5, 6, 7, 8}
output: -1

Ref: https://www.interviewbit.com

Find maximum sub array of positve number

 public int[] maxset(int[] A) {
       
        long tempSum = 0;
        long finalSum = 0;
        ArrayList<Integer> maxArray = new ArrayList<>();
        ArrayList<Integer> newArray = new ArrayList<>();
 
        for(int i=0;i<A.length;i++) {
            if(A[i]>=0){
                tempSum = tempSum+A[i];
                newArray.add(A[i]);
          
                if(tempSum>finalSum ||( tempSum==finalSum && newArray.size()>maxArray.size())) {
                    finalSum = tempSum;
                    maxArray = (ArrayList<Integer>)newArray.clone();
                    
                }
            }else {
                tempSum = 0;
                 newArray = new ArrayList<>();
                        
            }
        }
       
        int[] list = new int[maxArray.size()];
        for(int i=0;i<maxArray.size();i++) {
            list[i] = maxArray.get(i);
        }
       
        return list;
       
   
    }

input:  int[] arr = {1967513926, 1540383426, -1303455736, -521595368};
output: [1967513926, 1540383426]

input: int[] arr = {0,0,-1,0}
output: [0,0]



Sunday, 12 August 2018

TryWithResource java

public class TryWithResource {

        public static void main(String[] args) throws Exception {
            try {
                tryWithResourceException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            try {
                normalTryException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        private static void normalTryException() throws Exception {
            MyResource mr = null;
            try {
                mr = new MyResource();
                System.out.println("MyResource created in try block");
                if (true)
                    throw new Exception("Exception in try");
            } finally {
                if (mr != null)
                    mr.close();
               
            }

        }

        private static void tryWithResourceException() throws Exception {
            try (MyResource mr = new MyResource()) {
                System.out.println("MyResource created in try-with-resources");
                if (true)
                    throw new Exception("Exception in try");
            }
        }

        static class MyResource implements AutoCloseable {

            @Override
            public void close() throws Exception {
                System.out.println("Closing MyResource");
                throw new Exception("Exception in Closing");
            }

        }
}
output;


MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing

how its work:
tryWithResourceException called
print: MyResource created in try-with-resources
 before throw exception autoclose will call then print Closing MyResource and throw Exception in closing but its override by Exception in try


normalTryException called
print: MyResource created in try block and throw exception Exception in try but its overrride by finally



Saturday, 11 August 2018

MergeSort Program

Merge Sort:

public class MergeSort2 {

    public static void main(String args[]) {
        int[] arr = {1,12,3,8,2,1,7,9};
        mergeSort(arr, 0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }
   
    public static void mergeSort(int[] arr, int start, int end) {
        if(start<end) {                               //check start < mid then find mid and divide arr in parts 
            int mid = (start + end)/2 ;
            mergeSort(arr, start, mid);
            mergeSort(arr, mid+1, end);
            merge(arr, start, mid, end); //merge
        }
    }
   
    public static void merge(int[] arr, int start, int mid, int end) {
        int p = start ;
        int q = mid+1;
       
        int[] localArr = new int[end-start+1];
        int k = 0;
        for(int i=start;i<=end;i++) {
            if(p>mid) {
                localArr[k] = arr[q];
                k++;
                q++;
            }else if(q>end) {
                localArr[k] = arr[p];
                k++;
                p++;
            }else if(arr[p]<arr[q]) {
                localArr[k] = arr[p];
                p++;
                k++;
            }else {
                localArr[k]  =arr[q];
                q++;
                k++;
            }
        }
       
        for(int i=0;i<localArr.length;i++) {
            arr[start]  = localArr[i];
            start++;
        }
       
       
    }
   
}

How merge method work:
take an example below
[1,12 ,3,8 ||||||| ,2,1,7,9] start = 0,mid = 1,end = 3
we want to merge 0 to 3

p = 0
q=  mid+1 = 2;
take localarr of size end-start+1 = 4
k=0
loop---> start to < = end
if p reaches to mid then only right part need to insert localarr
if(p>mid) {
                localArr[k] = arr[q];
                k++;
                q++;
            }
if q reaches to end then only left part need to insert into localarr
else if(q>end) {
                localArr[k] = arr[p];
                k++;
                p++;
            }

if arr[p] <arr[q] it means need to insert p position element to localarr and increemt p

else if(arr[p]<arr[q]) {
                localArr[k] = arr[p];
                p++;
                k++;
            }

if arr[p]>arr[q] it means need to insert q position element to localarr and increment q
 else {
                localArr[k]  =arr[q];
                q++;
                k++;
            }

loop exit

now need to insert localarr to original array
  for(int i=0;i<localArr.length;i++) {
            arr[start]  = localArr[i];
            start++;
        }

QuickSort Program

QuickSort:

[5,9,3,15,13,7,1,8,18,14,4]

Steps:

we will choose first element as pivot
move all less than pivot on one side and other on one side

so we need to find the pivot element position
then partition in 2 parts first is before pivot and other is after pivot

public class QuickSort {
   
    public static void main(String args[]) {
        int arr[] = {10,3,16,8,9,1,15,6,18};
        quick_sort(arr,0, arr.length-1);
        System.out.println(Arrays.toString(arr));
    }
   
    static void quick_sort ( int A[ ] ,int start , int end ) {
           if( start < end ) {
                //stores the position of pivot element
                 int piv_pos = partition (A,start , end ) ;    
                 quick_sort (A,start , piv_pos -1);    //sorts the left side of pivot.
                 quick_sort ( A,piv_pos +1 , end) ; //sorts the right side of pivot.
           }
        }
   
    static int partition ( int A[],int start ,int end) {
        int i = start + 1;
        int piv = A[start] ;            //make the first element as pivot element.
        for(int j =start + 1; j <= end ; j++ )  {
        /*rearrange the array by putting elements which are less than pivot
           on one side and which are greater that on other. */

              if ( A[ j ] < piv) {
                     swap (A ,i , j );
                i += 1;
            }
       }
       swap ( A,start ,i-1  ) ;  //put the pivot element in its proper place.
       return i-1;                      //return the position of the pivot
    }
   
    public static void swap(int[] A,int first, int second) {
        int temp = A[first];
        A[first] = A[second];
        A[second] = temp;
    }
   
}


How partition work in above:
start = 0 , end = 10
[5,9,3,15,13,7,1,8,18,14,4]
piv = A[start] = 5
i = start+1 = 1;
loop--> j=start+1 to <=end and j++

first round of loop:  a[j]>piv so nothing change
                                  i= 1, j=2
second round of loop: a[j]<piv so swap i with j and increase i by1
  [5,3,9,15,13,7,1,8,18,14,4]
       i = 2, j=3
third round of loop:  a[j]>piv so nothing change
i=2,j=4 
fourth round of loop:  a[j]>piv so nothing change
i=2,j=5
fifth round of loop:  a[j]>piv so nothing change
i=2,j=6
seventh round of loop: a[j]<piv so swap i with j and increase i by1
  [5,3,1,15,13,7,9,8,18,14,4]
       i = 3, j=7
next few round no change till i=3, j=9
in last round i=3,j=10
a[j]<piv so swap i with j and increase i by1
  [5,3,1,4,13,7,9,8,18,14,15]
       i = 4


now loop break move pivot element to actual position
swap i-1 with start(pivot)

now pivot moved to actual postion

then we will sort the leftside of pivot and right side







Implement Least Recently Used (LRU) cache


 If item is present in cache, it is moved to front of the list and location is returned.

 If it is not present , a new page mapping is done. If cache is not full, a new entry is added to front otherwise least recently used entry is removed and then a new entry to front is added.

import java.util.HashMap;
import java.util.Map;

public class LRUCacheSample1 {
    DoubleLinkList start = null;
    DoubleLinkList end = null;
    int capacity = 5;
    int count = 0;
    Map<Integer, DoubleLinkList> map = new HashMap<>();
    class DoubleLinkList{
        DoubleLinkList next;
        DoubleLinkList prev;
        int key;
        int val;
      
        public DoubleLinkList(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
  
    void get(int key) {
        if(map.containsKey(key)) {
            DoubleLinkList existNode = map.get(key);
            moveNodeToFront(existNode);
        }
    }
  
    void add(int key,int val) {
        if(map.containsKey(key)) {
            DoubleLinkList existNode = map.get(key);
            existNode.val = val;
            moveNodeToFront(existNode);
        }else {
            DoubleLinkList node = new DoubleLinkList(key, val);
            if(count<capacity) {
                count = count+1;
                addNodeAtFront(node);
            }else {
                DoubleLinkList lastNode = map.remove(end.key);
                removeNode(lastNode);
                addNodeAtFront(node);
            }
      
        }
    }
  
    void removeNode(DoubleLinkList node) {
         end = end.prev;
         if(null!=end) {
             end.next = null;
         }
        node = null;
    }
  
    void addNodeAtFront(DoubleLinkList node) {
        node.next = start;
        if(null!=start) {
            start.prev = node;
        }
            start = node;
         if(end==null) {
             end = node;
         }
         map.put(node.key, node);
        
    }
  
    void moveNodeToFront(DoubleLinkList node) {
        DoubleLinkList pr = node.prev;
        DoubleLinkList nex = node.next;
        if(null!=pr) {
            pr.next = nex;
        }else {
            start = node;
        }
        if(null!=nex) {
            nex.prev = pr;
        }else {
            end = pr;
        }
      
         addNodeAtFront(node);
    }
  
    void print() {
        DoubleLinkList node = start;
        while(null!=node) {
            System.out.println("key is"+node.key+"val is"+node.val);
            node = node.next;
        }
    }
  
  
    public static void main(String args[]) {
        LRUCacheSample1 obj = new LRUCacheSample1();
        obj.add(5, 10);
        obj.add(2, 4);
        obj.add(3, 6);
        obj.add(6, 12);
        obj.add(8, 16);
        
        obj.print();
        obj.get(3);
        System.out.println("*****************");
        System.out.println("after get 3");
        obj.print();
      
        obj.add(9, 18);
        System.out.println("*****************");
        System.out.println("after add 9");
        obj.print();
      
        obj.add(2, 13);
        System.out.println("*****************");
        System.out.println("after update 2");
        obj.print();
      
      
    }
  
}
output::
key is8val is16
key is6val is12
key is3val is6
key is2val is4
key is5val is10
*****************
after get 3
key is3val is6
key is8val is16
key is6val is12
key is2val is4
key is5val is10
*****************
after add 9
key is9val is18
key is3val is6
key is8val is16
key is6val is12
key is2val is4
*****************
after update 2
key is2val is13
key is9val is18
key is3val is6
key is8val is16
key is6val is12

Ref: http://androidsrc.net/lru-cache-java-implementation/

Basics of Log4j

 Log4j is a Java library that specializes in logging.

At its most basic level, you can think of it as a replacement for System.out.println's in your code. Why is it better than System.out.println's? The reasons are numerous.

To begin with, System.out.println outputs to standard output, which typically is a console window. The output from Log4j can go to the console, but it can also go to an email server, a database table, a log file, or various other destinations.

Another great benefit of Log4j is that different levels of logging can be set. The levels are hierarchical and are as follows: TRACE, DEBUG, INFO, WARN, ERROR,


Ref: http://www.avajava.com/tutorials/lessons/what-is-log4j-and-how-do-i-use-it.html

Friday, 10 August 2018

Divide array into two sub-arrays such that their averages are equal

public class SplitArrayInTwoAverageEqual {

    public static void main(String[] args) {
        int[] arr = {1,5,7,2,0};
        int n = arr.length;
        int sum = 0;
        for(int i=0;i<n;i++) {
            sum+=arr[i];
        }
      
        int lsum = 0;
      
        for(int i=0;i<n-1;i++) {
            lsum+=arr[i];
            int rsum = sum-lsum;
            if(lsum*(n-i-1)==rsum*(i+1)) {
                System.out.println("first is: 0 to "+i+" and other is: "+(i+1) +" to "+ (n-1));
            }
        }
      
    }

}

output: first is: 0 to 1 and other is: 2 to 4

Get Base64 decoded and encoded


public static final String CHAR_ENCODING = "ISO-8859-1";
public static String getBase64Decoded(String toDecode) throws UnsupportedEncodingException{
        return new String(Base64.getDecoder().decode(toDecode.getBytes(CHAR_ENCODING)), Constants.CHAR_ENCODING);
    }



public static String getBase64Encoded(String toEncode) throws UnsupportedEncodingException{
        return new String(Base64.getEncoder().encode(toEncode.getBytes(CHAR_ENCODING)), Constants.CHAR_ENCODING);
    }


Decode base64 into bytes




public static final String CHAR_ENCODING = "ISO-8859-1";
    public static byte[] getBytesDecoded(String toDecode) throws UnsupportedEncodingException{
        return Base64.getDecoder().decode(toDecode.getBytes(CHAR_ENCODING));
    }




Thursday, 2 August 2018

@Component, @Service, @Controller, and @Repository in Spring

@controller: By using that annotation we do two things, first we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup.
For example, DispatcherServlet will look for @RequestMapping on classes which are annotated using @Controller but not with @Component.

They are scanned because they themselves are annotated with @Component annotation. If you define your own custom annotation and annotate it with @Component, then it will also get scanned with <context:component-scan>.

    @Component is a generic stereotype for any Spring-managed component or bean.
    @Repository is a stereotype for persistence layer.
    @Service is a stereotype for the service layer.
    @Controller is a stereotype for presentation layer (spring-MVC).

Ref: https://javarevisited.blogspot.com/2017/11/difference-between-component-service.html#more

Wednesday, 1 August 2018

Program for RemoveCharacter from String


public class RemoveCharacter {
    static char ch = 'e';
    public static void main(String args[]) {
        String str= "seuesheile";
        System.out.println(removeCharacter(str));
    }
   
    static String removeCharacter(String str){
        int index = str.indexOf(ch);
        if(index==-1) {
            return str;
        }
        return removeCharacter(str.substring(0, index)+str.substring(index+1,str.length()));
    }
   
}

output: sushil

Find the HighestOccurence in String

public class HighestOccurence {
    public static void main(String args[]) {
     
        String str = "sushil";
        char[] chars = str.toCharArray();
        int[] arr = new int[26];// number of char possible
        int maxCount = 0;
        char c = 0;
        for (int i = 0; i < chars.length; i++) {
            int index = chars[i] - 'a'; // reduce offset
            arr[index] = arr[index] + 1;

            if (arr[index] > maxCount) {
                maxCount = arr[index];
                c = chars[i];
            }
        }
        System.out.println(String.valueOf(c));
    }
   


output: s

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...