Saturday, May 30, 2015

Few Example for JAVA understanding

1. Write a Java method removeDuplicates that removes all duplicates in a given list.

 Solution:

import java.util.ArrayList;

public class DuplicateTest {

    public static void main(String args[])
    {
        ArrayList<String> list=new ArrayList<String>();
        list.add("good");
        list.add("better");
        list.add("best");
        list.add("best");
        list.add("first");
        list.add("last");
        list.add("last");
        list.add("last");
        list.add("good");
       
        System.out.printf("List Before Duplicate Removal:%s",list);
       
        removeDuplicatesMethod(list);
       
        System.out.printf("\nList After Duplicate Removal:%s",list);
    }

    private static void removeDuplicatesMethod(ArrayList<String> list) {
        // TODO Auto-generated method stub
        for(int i=0;i<list.size();i++)
        {
            for(int k=i+1;k<list.size();k++)
            {
                if(list.get(i).equals(list.get(k)))
                {
                    list.remove(k);
                    k--;
                }
            }
        }
    }
   
   
}

2.  Write a Java method testForSum which determines whether a given array of integers contains three entries whose sum is equal to a given integer.
Solution:

public class TestSumImplementation {
   
    public static void main(String args[])
    {
      
        int[] testdata={5, 1, 23, 21, 17, 2, 3, 9, 12};
        int sum=5;
      
        boolean result= testForSum(testdata,sum);
        System.out.print(result);
    }

    private static boolean testForSum(int[] testdata, int sum) {
        // TODO Auto-generated method stub
        for(int i=0;i<testdata.length-2;i++)
        {
            for(int j=i+1;j<testdata.length-1;j++)
            {
                for(int k=j+1;k<testdata.length;k++ )
                    if(testdata[i]+testdata[j]+testdata[k]==sum) return true;
            }
        }
        return false;
    }
  
   
}

 3. Create your own linked list

Solution:

public class ListNode {
    Object data;
    ListNode nextNode;
  
    public ListNode(Object object)
    {
        data=object;
    }

    public ListNode(Object object,ListNode Node)
    {
        data=object;
        nextNode=Node;
    }
  
    Object getObject()
    {
        return data;
    }
  
    ListNode getNext()
    {
        return nextNode;
    }
}


public class LinkList {
    private ListNode firstNode;
    private ListNode lastNode;
    private String name;
   
    public  LinkList()
    {
        this("list");
    }

    public  LinkList(String listName)
    {
        name=listName;
    }
   
    public void add(Object obj)
    {
        if(isEmpty())
            firstNode=lastNode=new ListNode(obj);
        else
            firstNode=new ListNode(obj,firstNode);
    }
   
    public boolean find(Object obj)
    {
        if(isEmpty())
            return false;
        else
        {
            ListNode current=firstNode;
            while(current.nextNode!=null)
            {
                current=current.nextNode;
                if(obj==current.data)
                    return true;
            }
            return false;
        }
       
    }
   
   
    public boolean isEmpty()
    {
         if(firstNode==null)
             return true;
         else
             return false;
    }
   
    public String toString()
    {
        if(isEmpty())
            return "Empty List";
        else
        {
            ListNode current=firstNode;
            String result="[";
            while(current.nextNode!=null)
            {
                current=current.nextNode;
                result+=(String)current.data+",";
                   
            }
            result+=lastNode.data+"]";
            return result;
        }
    }
   
    public static void main(String args[])
    {
        LinkList list=new LinkList();
       
        list.add("Straight");
        System.out.println(list.toString());
        list.add("Bent");
        System.out.println(list.toString());
        list.add("Equals");
        System.out.println(list.toString());
       
        list.add("Well");
        System.out.println(list.toString());
        list.add("Storm");
        System.out.println(list.toString());
        //System.out.println(list.toString());
        System.out.printf("\nSearch result of well:%s",list.find("Well"));
        System.out.printf("\nSearch result of Strength:%s",list.find("Strength"));
       
       
       
    }
}
4. Permutation:

import java.util.ArrayList;
import java.util.LinkedList;

public class Permutation {
    public static void main(String[] args) {
        for(int[] a :permutationsOf(new int[]{1,2,3,4})){
            for(int b:a){
                System.out.print(b+",");
            }
            System.out.println();
           
        }
       
    }
    static ArrayList<int[]> permutationsOf(int[] arr) {
        ArrayList<int[]> result = new ArrayList<int[]>();
        if (arr.length == 1) {

            result.add(arr);
            return result;
        } else {
            int first=arr[0];
            int[] rest=new int[arr.length-1];
            for(int i=1;i<arr.length;i++){
                rest[i-1]=arr[i];
            }
            ArrayList<int[]> simpler=permutationsOf(rest);
            for(int[] permutation:simpler){
                ArrayList additions=insertAtAllPositions(first,permutation);
                result.addAll(additions);
            }
            return result;
           

        }
    }

    private static ArrayList insertAtAllPositions(int first, int[] permutation) {
        // TODO Auto- generated method stub
        ArrayList<int[]> res=new ArrayList<int[]>();
        for(int i=0;i<permutation.length+1;i++){
            LinkedList<Integer> ll=new LinkedList<Integer>();
            for(int j=0;j<permutation.length;j++){
                ll.add(permutation[j]);
               
               
            }
            ll.add(i, first);
            int[] r=new int[ll.size()];
            int count=0;
            for(int z:ll){
                r[count++]=z;
            }
            res.add(r);
        }
        return res;
    }


}

5. Object Restriction:

public class RestrictInstance {
   
        private static final int limit_ =5; //Set this to whatever you want to restrict
        private static int count =0;
        private RestrictInstance(){}
        public static synchronized RestrictInstance getInstance(){
            if(count<limit_){
                RestrictInstance myClass= new RestrictInstance();
                count++;
                return myClass;
            }
            return null;
        }
       
        public static void main(String args[])
        {
            RestrictInstance a= RestrictInstance.getInstance();
            RestrictInstance a1= RestrictInstance.getInstance();
            RestrictInstance a2= RestrictInstance.getInstance();
            RestrictInstance a3= RestrictInstance.getInstance();
            RestrictInstance a4= RestrictInstance.getInstance();
            RestrictInstance a5= RestrictInstance.getInstance();
           
            System.out.println(a.toString());
            System.out.println(a3.toString());
            System.out.println(a4.toString());
            //System.out.println(a5.toString());
        }
}

Solution to problem 1
package prob1;

public class MyStringList {
      private int size = 0;
      private final int INIT_ARR_SIZE = 2;
      private String[] strArray;
     
      public MyStringList(){
            strArray = new String[INIT_ARR_SIZE];
      }
      public void add(String s) {
            if(size >= strArray.length) resize();
            strArray[size++]=s;
      }
      public boolean find(String s) {
            for(int i = 0; i < size; ++i) {
                  if(s.equals(strArray[i])) return true;
            }
            return false;
      }
      public String get(int i) {
            if(i < 0 || i >= size) return null;
            return strArray[i];
      }
      private void resize() {
            System.out.println("Resizing from size "+strArray.length +"to "+2*strArray.length);
            String[] temp = new String[2*strArray.length];
            for(int i = 0; i < strArray.length; ++i) {
                  temp[i] = strArray[i];
            }
            strArray = temp;
      }
      public static void main(String[] args) {
            MyStringList list = new MyStringList();
     
            for(int i = 0; i < 64; ++i) {
                  list.add("a"+i);
            }
            System.out.println("looking for a3 "+list.find("a3"));
            System.out.println("value at position 43 "+list.get(43));
      }
}

Solution to Problem 2
package prob2;

import java.util.HashMap;
import java.util.Iterator;

public class Employee {
      private String firstName;
      private String lastName;
      private HashMap salaryRecord=new HashMap();
     
      public void addEntry(String date, double salary) {
            salaryRecord.put(date,salary);
      }
      public void printPaymentAmount(String date) {
            Double salaryObject = (Double)salaryRecord.get(date);
            if(salaryObject == null){
                  System.out.println(firstName+" "+lastName+" did not receive a paycheck on "+date);
                 
            }
            else {
                  System.out.println(firstName+" "+lastName+" was paid "+salaryObject.doubleValue()+" on "+date);
            }
           
      }
      public void printAveragePaycheck() {
            Iterator it = salaryRecord.keySet().iterator();
            double accum = 0.0;
            int count = 0;
            while(it.hasNext()){
                  String nextDate = (String)it.next();
                  Double sal = (Double)salaryRecord.get(nextDate);
                  accum += sal.doubleValue();
                  ++count;
            }
            System.out.println("Average paycheck for "+firstName+" "+lastName+" was "+accum/count);
      }
     
      public static void main(String[] args) {
            Employee e = new Employee();
            e.setFirstName("Jim");
            e.setLastName("Jones");
            for(int i = 0; i < 12; ++i) {
                  e.addEntry(i+"/15/2006", 3070+5*i);
            }
            e.printPaymentAmount("3/15/2006");
            e.printPaymentAmount("5/15/2005");
            e.printAveragePaycheck();
           
      }
      public String getFirstName() {
            return firstName;
      }
      public void setFirstName(String firstName) {
            this.firstName = firstName;
      }
      public String getLastName() {
            return lastName;
      }
      public void setLastName(String lastName) {
            this.lastName = lastName;
      }

}

Tuesday, April 7, 2015

25 Funny Situations Of A Programmer's Life



1. When the project manager enters the office




2. When I try to fix a bug at 3 in the morning



3. When I'm told that the module on which I have worked all the week will never be used




4. When the code that I have not tested on dev works perfectly in production




5. When the sales people announce they have sold our product to the customer




6. When sysadmin finally gives us the root access




7. When I launch my script for the first time after several hours of development




8. When I go off for the weekend while everyone else is still trying to fix bugs




9. When the boss is looking for someone to urgently fix a difficult bug




10. When a thing that worked on Friday no longer works on Monday




11. When a bug goes unnoticed during a presentation




12. When a newbie suggests to add a new feature to project




13. When I realize that I have been blocked for two hours because of a forgotten semicolon




14. When the project manager suddenly looks on my screen




15. When customer wants to change specification 2 days before pushing to production




16. When my script finally worked




17. When I'm told that my code is broken in production




18. When I find a solution without searching Google




19. When the intern tells me that "the tests are for those who can not program"




20. When I manage to replace 200 lines of the algorithm by only 10 lines




21. When I return to development of my code that wasn't commented




22. When they tell me the website has to be supported by IE6




23. When a misformed sql query actually returns me the correct results




24. When I start coding without doing analysis first




25. When project manager thinks that I can handle whole project all by myself


Please do share if you liked this article!