Saturday, 28 February 2015

Constrcutor VS static functions to create instances

 Source Effective Java

/*Item 1: Consider static factory methods instead of constructors
 ## Use static method to make instance controlled classes

 *        The normal way for a class to allow a client to obtain an instance of itself is to provide
 *    a public constructor. There is another technique that should be a part of every
 *    programmer’s toolkit. A class can provide a public static factory method, which is
 *  simply a static method that returns an instance of the class. Here’s a simple example
 *  from Boolean (the boxed primitive class for the primitive type boolean). This
  * method translates a boolean primitive value into a Boolean object reference:
*/

        public static Boolean valueOf( boolean b) {
            return b ? Boolean.TRUE : Boolean.FALSE ;
        }
/*page - 27
            One advantage of static factory methods is that, unlike constructors, they
            have names. If the parameters to a constructor do not, in and of themselves,
            describe the object being returned, a static factory with a well-chosen name is easier
            to use and the resulting client code easier to read
           
            page - 29
            A second advantage of static factory methods is that, unlike constructors,
they are not required to create a new object each time they’re invoked This
allows immutable classes (Item 15) to use preconstructed instances, or to cache
instances as they’re constructed, and dispense them repeatedly to avoid creating
unnecessary duplicate objects



           
           
*/
   

Finding comman characters between two strings aka String intersection

<?php

    /**
    * function to find comman alphabets in two string
    * @params $strOne and $strTwo , two strings to compare
    *
    * @return $comman string consisting a string of comman  characetrs
    */
    function commanAlphabets($strOne , $strTwo)
    {
   
        echo  " String to comapre  :  $strOne with $strTwo " ;
       
        //convert to arrays
        $charArrayOne = str_split($strOne);
        $charArrayTwo = str_split($strTwo);
       
        //implode to find intersections
        $comman =  array_unique (array_intersect($charArrayOne , $charArrayTwo));
       
        return $comman;
    }
   
   
    $result = commanAlphabets("AMITABH BACHCHAN" , "RAJNIKANT");
   
   
        echo "<br> Comman characters are as follows : <br> ";
        //print string of comman characters
        echo implode($result);
   
?>

Finding comman characters in a given string

<?php
    //given string
    $str  = "JIMMY AND JOLLY";
    echo  "Given String :  $str <br>" ;
   
    //convert to character array
    $charArray = str_split($str);
   
    //$result["charBooleans"] = array_fill(0, 25, 0);
    $result["charBooleans"] = new SplFixedArray(26);
   
   
    for( $i = 0 , $len =  count($charArray)    ; $i < $len ; ++$i  )
    {
       
        if($charArray[$i] == ' ')
            continue;
       
        for( $j = $i + 1   ; $j < $len  ; ++$j  )
        {
           
            //check if characters are same
                if( $charArray[$i] == $charArray[$j] &&  $charArray[$i] != ' ' && $result["charBooleans"][$i] != 1 )
            {
                //ord() converts char to ASCII value
                $num =   ord($charArray[$i]) - 65;
                 //echo "num :  $num and char  $charArray[$i]: <br>";
                $result["charBooleans"][$num] = 1;
                //the character exist in string hence break from inner loop
                break;
            }
           
        }
    }
   
    for( $i = 0 , $len = count($result["charBooleans"])   ; $i < $len ; ++$i  )
    {
        if($result["charBooleans"][$i] == 1)
        {
            echo chr(65 + $i) ;
            echo "<br>";
        }
    }   
?>

Print all valid combinations of n-pairs of parentheses



    For such recursive problems check if f(n) can be built from f(n-1)  , by inserting an instance of n = 1
    This is a hint for general recursive problem
   
    Example : n = 1 : ()
              n = 2 : ()() , (())
              n = 3 : ()()() , (())() , () (()) , (()()) , ((()))
             
    f(3) can be found from f(3-1) , i,.e  f(2) , by adding a single pair of parenthesis to f(3-1) inside every existing pair of parenthesis
   
    Eg. -  n = 2 : ()() -
                         (())()  // inserted after first left parenthesis
                         () (()) // inserted after second left parenthesis
                         ()()()  // inserted at beginning
                        
                    (()) -
                          (()())  // inserted after first left parenthesis
                          ((()))  // inserted after second left parenthesis
                          () (()) // inserted at beginning
     
      Since  () (()) occurs twice so use of set is required
       Placing a pair at end would reduce to previous case as already did
       eg -    (())()  inserted at end of (()) is same as inserted after first left parenthesis in ()() 


public   Set<String> generateParen(int remainder)
{
    //HashSet will automatically check that no same values are inserted in set
    Set<String> set = new HashSet<>();
    //base case
    if( remainder == 0 )
    {
        set.add("");
    }
   
    else
    {
        //recurse to f(n-1)
        Set<String> prev =  generateParen(remainder-1);
       
        for(Strring str : prev)
        {
            for( int i = 0 ; i < str.length() ; ++i)
            {
                //if a left parenthesis is found
                if(str.charAt(i) == '(')
                {
                    String s = insertParenAt(str, i );
                    set.add(s);
                }
            }
           
            //insert at beginning
            set.add("()" + str);
        }
       
   
    }

}

public String insertParenAt (String parent , int index)
{
    String left = parent.substring(0,index+1);
    String right = parent.substring(index+1 , parent.length());
    return left+ "()" + right ;
}