Tag Archives: Data types

Using PHP’s array_diff in Algorithm Development

array_diff can be really powerful. Once you’ve to find the different elements between two arrays you’ve to use array_diff. Here’s a case when you can use it while coding a simple algorithm.

The Task

You’ve one array with tickets of linked destinations – so you start from one city to another, than next and so on. Each element is an array with “from” and “to” destinations:

$inputTickets = array(
    0 => array('from' => 'barcelona', 'to' => 'madrid'),
    1 => array('from' => 'sofia', 'to' => 'paris'),
    2 => array('from' => 'madrid', 'to' => 'milano'),
    3 => array('from' => 'paris', 'to' => 'barcelona'),
    4 => array('from' => 'cupertino', 'to' => 'sofia'),
    5 => array('from' => 'milano', 'to' => 'valencia'),
    6 => array('from' => 'valencia', 'to' => 'nice'),
    7 => array('from' => 'mountain view', 'to' => 'cupertino'),
);

It’s easy to construct two arrays – the “from” destinations array and the “to” destinations array, and here the easiest way to get the starting point of the whole trip, because of the fact that these are linked tickets.

$fromDestinations = $toDestinations = array();
 
foreach ($inputTickets as $k => $v) {
    $fromDestinations[] = $v['from'];
    $toDestinations[]   = $v['to'];
}
 
// and finally get the starting point
$startPoint = array_diff($fromDestinations, $toDestinations);

Conclusion

Beside of knowing several algorithm techniques, there’s also need of knowing the language syntax and possibilities – in that case PHP’s

PHP: What is More Powerful Than list() – Perhaps extract()

list() in PHP

Recently I wrote about list() in PHP which is indeed very powerful when assigning variable values from array elements.

$a = array(10, array('here', 'are', 'some', 'tests'));
list($count, $list) = $a;

Actually my example in the post was not correct, because I wrote that you can pass an associative array, but the truth is that you cannot, and thus the array should be always with numeric keys. After noticing the comments of that post, and thanks to @Philip,  I searched a bit about how this problem can be overcome.

There is a Solution

As always PHP gives a perfect solution! You can see on the list() doc page that there is a function that may help you use an associative array.

Extract

extract() is perhaps less known than list(), but it does the right thing!

$a = array('count' => 10, 'list' => array('here', 'are', 'some', 'tests'));
extract($a);
 
echo $count;    // 10
print_r($list); // array('here'....

Note that now both $count and $list are defined.

PHP: What is More Powerful Than list()

First of all list() is not an unknown method in the PHP community, where almost every PHP developer knows what it does. The pity is that it has, perhaps, remained useless, although there is hidden power in it!

What is list()?

Let’s assume you’ve two variables and one array with two elements:

$arr = array(1, 2);
$a = $arr[0];
$b = $arr[1];
// now a == 1, and b == 2

Maybe the easiest way to assign to the first variable the value of the first element of the array, and to the second variable the value of the second element of the array is to use list():

list($a, $b) = array(1, 2);
// again a == 1, and b == 2

Note that you can do the same with as many variables/array elements you want.

The funny thing is that nobody use it, while I see at least one perfect usage. You can think of a typical admin panel of any web system. For sure any developer has programmed the typical table page containing a list of “things” and a paging to switch the result set page. It’s like the posts page from the WordPress admin panel, or a search result page in Google, where you’ve one page of results and at the bottom – a number of pages where you can go to another page of the search results.

What I’ve seen in almost every project is that typically the developers prefer to set the results for the page into one list returned from one method and the count of the entire result set is returned by another method.

Thus most of the times there are two methods, performing most commonly a database queries. Something like – getList($offset, $limit) and getCount() where the first one returns the page and the second one returns the count of the result set.

This will result into two methods, two calls and two lines of code:

function getList($offset, $limit)
{
	...
	// although the entire result set contains
	// 5 elements by limiting it from the parameters
	// only three are returned
	return $list; // where $list = array('title1', 'title2', 'title3');	
}
 
function getCount()
{
	...
	// here's returned the count
	// of the entire result set
	return $count; // where $count = 5;	
}
 
$list  = getList(0, 3);
$count = getCount();

What actually you can do is to perform both queries in one method, perhaps called getItems($offset, $limit) where the returned value is an array containing both the list of results and the count:

function getItems($offset, $limit)
{
	...
	return array('list' => $list, 'count' => $count);
}

And finally when calling this method to list() that into the two variables – single lined.

list($list, $count) = getItems(0, 3);

Friday Algorithms: A Data Structure: JavaScript Stack

Algorithms and Data Structures

stack

Instead of writing about “pure” algorithms this time I’ve decided to write about data structures and to start with a stack implementation in JavaScript. However algorithms and data structures live together since the very beginning of the computer sciences. Another reason to write about data structures is that many algorithms need a specific data structure to be implemented. Most of the search algorithms are data structure dependent. You know that searching into a tree is different from searching into a linked list.

I’d like to write more about searching in my future algorithm posts, but first we need some data structure examples. The first one is, as I mentioned – stack.

Implemented in JavaScript this is really a simple example, which don’t need much to be understood. But in first place what is a stack?

You can thing of the “computer science” stack as a stack of sheets of paper, as it’s shown on the picture. You’ve three basic operations. You can add new element to the stack by putting it on the top of the stack, so the previous top of the stack becomes the second element in the stack. Another operation is to “pop” from the stack – remove the “first” element in the stack – the top most element, and to return it. And finally print the stack. This is difficult to define as an operation, but let say you’ve to show somehow every element from the stack.

Here’s a little diagram:

Stack

Source Code

At the end some source code:

var node = function()
{
    var data;
    var next = null;
}
 
var stack = function()
{
    this.top = null;
 
    this.push = function(data) {
        if (this.top == null) {
            this.top = new node();
            this.top.data = data;
        } else {
            var temp = new node();
            temp.data = data;
            temp.next = this.top;
            this.top = temp;
        }
    }
 
    this.pop = function() {
        var temp = this.top;
        var data = this.top.data;
        this.top = this.top.next;
        temp = null;
        return data;
    }
 
    this.print = function() {
        var node = this.top;
        while (node != null) {
            console.log(node.data);
            node = node.next;
        }
    }
}
 
var s = new stack();
 
s.push(1);
s.push(2);
s.push(3);
 
s.print();
 
var a = s.pop();
 
s.print();