Skip to main content

Implement BinarySearch with php


class BinarySearch
{
    private $start              = null;
    private $end                = null;
    private $calculatedLength   = null;
    private $elements           = array();
    private $searchingEliment   = null;



    /**
     * @param $searchEliment
     * @param array $eliments
     * @return int
     */
    public function search($searchEliment, array $eliments = array())
    {
        $this->searchingEliment = (int) $searchEliment;
        $this->elements         = $eliments;
        $totalElement           = count($this->elements);
        $currentElement         = current($this->elements);
        $this->start            = 0;
        $this->end              = $totalElement - 1;

        if (($totalElement == 0) || ($totalElement == 1
                && $currentElement != $this->searchingEliment))
            return -1;

        if ($totalElement == 1 && $currentElement == $this->searchingEliment)
            return $this->start;

        while (true) {

            $this->calculatedLength = $this->start + $this->end;

            if ($this->calculatedLength == 1) {
                if ($this->elements[$this->start] == $this->searchingEliment) {
                    return $this->start;
                } else if ($this->elements[$this->end] == $this->searchingEliment) {
                    return $this->end;
                } else {
                    return -1;
                }
            }

            $mid = ceil($this->calculatedLength / 2);

            if ($this->elements[$mid] == $this->searchingEliment)
                return $mid;

            if ($this->end == $mid)
                return -1;

            if ($this->elements[$mid] < $this->searchingEliment)
                $this->start = $mid;

            if ($this->elements[$mid] > $this->searchingEliment)
                $this->end = $mid;
        }

    }
}





class BinarySearchTest extends PHPUnit_Framework_TestCase
{

    public function testBinarySearchReturnIndex()
    {
        $binarySearch = new RequiresiveBinarySearch();
        $this->assertEquals($binarySearch->search(2, array(1, 2)), 1);


        $this->assertEquals($binarySearch->search(3, array()), -1);
        $this->assertEquals($binarySearch->search(3, array()), -1);

        $this->assertEquals(-1, $binarySearch->search(3, [1]));
        $this->assertEquals(0,  $binarySearch->search(1, [1]));

        $this->assertEquals(0,  $binarySearch->search(1, [1, 3, 5]));
        $this->assertEquals(1,  $binarySearch->search(3, [1, 3, 5]));
        $this->assertEquals(2,  $binarySearch->search(5, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(0, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(2, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(4, [1, 3, 5]));
        $this->assertEquals(-1, $binarySearch->search(6, [1, 3, 5]));

        $this->assertEquals(0,  $binarySearch->search(1, [1, 3, 5, 7]));
        $this->assertEquals(1,  $binarySearch->search(3, [1, 3, 5, 7]));
        $this->assertEquals(2,  $binarySearch->search(5, [1, 3, 5, 7]));
        $this->assertEquals(3,  $binarySearch->search(7, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(0, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(2, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(4, [1, 3, 5, 7]));
        $this->assertEquals(-1, $binarySearch->search(6, [1, 3, 5, 7]));
        $this->assertEquals(4, $binarySearch->search(67, [1, 3, 5, 7, 67]));
        $this->assertEquals(-1, $binarySearch->search(8, [1, 3, 5, 7]));

    }


}

DecoratorPattern


interface DecoratorInterface
{
    /**
     * @return mixed
     */
    public function render();
}






class HTMLDecorator implements DecoratorInterface
{
    protected $book = null;

    public function __construct($book_object)
    {
        $this->book = $book_object;
    }

    public function render()
    {
        $properties = get_object_vars($this->book);

        echo '<ul>';
        foreach($properties as $key => $value) {
            echo '<li>' . $key . ' -- ' . $value . '</li>';
        }
        echo '</ul>';
    }
}




class JSONDecorator implements DecoratorInterface
{
    protected $book = null;

    public function __construct($book_object)
    {
        $this->book = $book_object;
    }

    public function render()
    {
        echo json_encode($this->book);
    }
}






class PatternTest {

    public $decorator;

    public function __construct(DecoratorInterface $decorator)
    {
        $this->decorator = $decorator;
    }
}


$book = new stdClass();
$book->title = "Patterns of Enterprise Application Architecture";
$book->author_first_name = "Martin";
$book->author_last_name = "Fowler";

echo '<h1>HTML Decorator</h1>';

$htmlDecorator = new HTMLDecorator($book);
$htmlDecorator->render();

echo '<h1>JSON Decorator</h1>';

$jsonDecorator = new JSONDecorator($book);
$jsonDecorator->render();



Problem solution of CodeWare

function createFebonacci(nth){  
  return Math.round((Math.pow(1.6180339, nth))/Math.sqrt(5));  
}

function createEvenFebonacci() {
  var nth = 0;
  var febo = 0;
  var result = 0
  var suquence = [];
  while(1) {
    febo = createFebonacci(nth++);
    console.log(febo);
    if (febo % 2 == 0) {
      suquence.push(febo);
    }
    if (febo > 4000000) {
      console.log(suquence);
	for (var i = 0; i < suquence.length; i++) {
	    result += sesuquence[i];				
	}	
      break;
    }
  }
   console.log(result);
}
createEvenFebonacci();



var capitals = function (word) {
	var indexs = [];
  for (i = 0; i < word.length; i++ ) {
    var charcter = word[i];
    if (charcter == word[i].toUpperCase()) {
      indexs.push(i);
    }
  }
  return indexs;
};






function Counter(){
  this.value = 0;
}

Counter.prototype.incr = function() {
  this.value++;
}

Counter.prototype.toString = function() {
  return this.value;
}



function isIsogram(str) {
  var charcters = [];
  for (var i = 0; i < str.length; i++) {
    if (typeof charcters[str.toUpperCase().charCodeAt(i)] == 'undefined')
        charcters[str.toUpperCase().charCodeAt(i)] = str[i]
    else 
      return false;        
  }
  return true;  
}



Implement function createTemplate which takes string with tags wrapped in {{brackets}}
as input and returns closure, which can fill string with data (flat object, where keys are tag names).

let personTmpl = createTemplate("{{name}} likes {{animalType}}");
personTmpl({ name: "John", animalType: "dogs" }); // John likes dogs

function createTemplate(template) {     
  
  return function(obj) {

    for (attr in obj) {      
      var pattern = new RegExp('{{' + attr + '}}', "g");      
      var matchText = pattern.test(template) ? obj[attr] : '' ;
      console.log(matchText);
      template = template.replace(pattern,matchText );             
    }        
    
    return template;
  }
}

var personTmpl = createTemplate("{{name}} likes {{animalType}}");
personTmpl({ names: "John", animalType: "dogs" }); // John likes dogs

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.


//an = a1 + (n - 1)d
//Sn = (n/2)(a1 + an)

function solution(number){  
    return getSum(3, number -1 ) + getSum(5, number- 1) + getSum(15, number- 1);
}
    
function getSum(difference,number) {  
  var frequency = Math.floor(number / difference);  
  var lastNumber = difference + (frequency - 1) * difference;
  return (frequency/ 2) * (difference + lastNumber);
}    

solution(19)

Function borrowing and currying

Function borrowing…..

var person = {
	firstName : "atik",
	lastName : 'haque'
	getName : function (){
		return this.fristName + "" + this.lastName;
	}
}

var newPerson = {
	firstName : 'kamal',
	lastName : 'khan' 
}

person.getName.call(newPerson);

Function currying…..

function MultipleBy(a,b) {
	return a * b;
}

var multipleByThree = MultipleBy.bind(this,3);
multipleByThree(5);

In javascript Creation phase and Execution phase

In javascript Creation phase and Execution phase. First phase is Creation phase.

In that phase create memory space for every variable and function that you write in your code.
So when the execution phase will run it can find it in memory.

And when the execution phase run it compile line by line and execute the code.Execution phase run single threaded Synchronous manner that means always execute single line at a time in order.

What is the difference between == and === operator

Firstly

 "==" 

this equality check operator try to Coercion the two value

like

 3 == '3' 

in this case == operator try convert ‘3’ in number thats why

 3 == '3'  return true;

another example

 1 < 2 < 3 

what might you think the result will be ? result is true.
On the other hand

 3 < 2 < 1 

resutl also true. You may be confuse ……..
let see what is going here…

firstly example 1

 "1 < 2 < 3" 

this

 < 

comparison operator Associativity is left-to-right so this

'<'

comparison operator Associativity is left-to-right so

 1 < 2 

execute first and result true

then

 true < 3;

here true is going to convert number and converted result is 1

then

 1 < 3 

result is true.

But on the other hand

 '===' 

Strict Equality operator dont compare in this fashoine.

It just compare the value without convert or Coercion.

Like

 3 == '3' return true;

but

 3 === '3' return false;

So main difference between

 "==" 

and

 "==="

this

 "==" 

convert the value

and this

 "===" 

dont convert the value

Code to interface not in implementation

This principle is really about dependency relationships which have to be carefully managed in a large app. – Erich Gamma

The interface represents “what” the class can do but not “how” it will do it, which is the actual implementation.

When you program to interface not implementation your code become more decouple and easy to maintenance.

For example….

 
class Mysql
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    { 
        $this->db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

Here Mysql fully depend on PDO class. MySql tightly couple with PDO and it is hard to test with unit testing. Now use this class to interact with other class

 
class Book {

    private $database = null;

    public function __construct() {
        $this->database = new Mysql();
        $this->database->connect('mysql:host=localhost;dbname=oop', 'root', '');
    }

    public function getAll()
    {
       $books = $this->database->query('SELECT * FROM books ORDER BY id DESC');
       print_r($books);
    }
}

$user = new Book();
$user->getAll();

This books class also have some porblem

  • Book class fully dependent with Mysql class and it is hard to unit test.
  • If you need another model or class you have to write this mysql connection code again which is against the law DRY(dont repeat your self).
  • If you need another database or change database credential then you have to modify all class which is difficult to maintenance.
  • There is no need to know about database connection and query related work by Book class which is against (SOLID) single responsibility principle.
    So what is the solution

Solution is dependency injection or inversion which is SOLID D. Find out the dependency of the class and inject those dependency through method.

 
class Book {

    private $database = null;

    public function __construct(Mysql $database) {
        $this->database = $database;
    }

    public function getAll()
    {
        $books = $this->database->query('SELECT * FROM books ORDER BY id DESC');
        print_r($books);
    }
}



$database = new Mysql();
$database->connect('mysql:host=localhost;dbname=oop', 'root', '');
$user = new User($database);
$user->getUsers();

After refactor the class now we can easily inject the database connection and book class does not worry about the database connection related work so it is fully single responsible. And easily test this class. But there is a problem and it is Book class only work with MySql Class.Solve this problem we can use Dependency inversion principle

 
interface DB
{
    public function connect($dsn, $user = '', $pass = '');
    public function query($query);
}

class Mysql implement DB	
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    { 
        $this->db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

we can also write others database connection class which also implement DB interface.

 

class Sqlite implements DB
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this->db = new PDO($dsn);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

Here come our main focus that is code to interface not to implementation

 


class Book
{

    private $database = null;

    public function __construct(DB $database)
    {
        $this->database = $database;
    }

    public function getAll()
    {
        $books = $this->database->query('SELECT * FROM books ORDER BY id DESC');
        print_r($books);
    }
}


$database = new Mysql();
$database->connect('mysql:host=localhost;dbname=oop', 'root', '');
$book = new Book($database);
$book->getAll();

Now we can easily inject any database connection and query related class which implement DB interface.