<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>USD &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/usd/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Dijkstra Shortest Path in a Graph</title>
		<link>/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/</link>
		<comments>/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/#comments</comments>
		<pubDate>Mon, 15 Oct 2012 14:12:50 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[BFS algorithm]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Dijkstra algorithm]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Distance]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[library SPL]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[The algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3381</guid>
		<description><![CDATA[Introduction We already know how we can find the shortest paths in a graph starting from a given vertex. Practically we modified breadth-first search in order to calculate the distances from s to all other nodes reachable from s. We know that this works because BFS walks through the graph level by level. Some sources &#8230; <a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Dijkstra Shortest Path in a Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We already know how we can find the shortest paths in a graph starting from a given vertex. Practically we modified breadth-first search in order to calculate the distances from s to all other nodes reachable from s. We know that this works because BFS walks through the graph level by level.</p>
<figure id="attachment_3397" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png"><img src="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png" alt="BFS Shortest Paths" title="BFS Shortest Paths" width="620" height="399" class="size-full wp-image-3397" srcset="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png 620w, /wp-content/uploads/2012/10/1.-BFS-Shortest-Paths-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">BFS is often used to find shortest paths between a starting node (s) and all other reachable nodes in a graph!</figcaption></figure>
<p>Some sources give a very simple explanation of how BFS finds the shortest paths in a graph. We must just think of the graph as a set of balls connected through strings. </p>
<figure id="attachment_3398" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png"><img src="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png" alt="The Graph as Balls and Strings" title="The Graph as Balls and Strings" width="620" height="399" class="size-full wp-image-3398" srcset="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png 620w, /wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can think of a graph as a set of balls connected through strings!</figcaption></figure>
<p>As we can see by lifting the ball called “S” all other balls fall down. The closest balls are directly connected to “s” and this is the first level, while the outermost balls are those with longest paths.</p>
<figure id="attachment_3399" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png"><img src="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png" alt="The Graph as Balls and Strings Levels" title="The Graph as Balls and Strings Levels" width="620" height="399" class="size-full wp-image-3399" srcset="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png 620w, /wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Breadth-first search works much like the image above &#8211; it explores the graph level by level, thus we&#8217;re sure that all the paths are the shortest!</figcaption></figure>
<p>Clearly edges like those between A and B doesn’t matter for our BFS algorithm because they don’t make the path from S to C through B shorter. This is also known as the triangle inequality, where the sum of the lengths of two of the sides of the triangle is always greater than the length of the third side.</p>
<figure id="attachment_3400" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/4.-Triangle-inequality.png"><img src="/wp-content/uploads/2012/10/4.-Triangle-inequality.png" alt="Triangle inequality" title="Triangle inequality" width="620" height="399" class="size-full wp-image-3400" srcset="/wp-content/uploads/2012/10/4.-Triangle-inequality.png 620w, /wp-content/uploads/2012/10/4.-Triangle-inequality-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">What the triangle inequality says us is that if we have a direct edge between two nodes &#8211; that must be the shortest path between them!</figcaption></figure>
<p>We must only answer the question is BFS the best algorithm that finds the shortest path between any two nodes of the graph? This is a reasonable question because as we know by using BFS we don’t find only the shortest path between given vertices i and j, but we also get the shortest paths between i and all other vertices of G. This is an information that we actually don’t need, but can we find the shortest path between i and j without that info?<span id="more-3381"></span></p>
<p>The answer is simply “no”! Practically depth-first search can’t help us. Even worse &#8211; we can find paths that are far not the shortest ones.</p>
<figure id="attachment_3401" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png"><img src="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png" alt="DFS and shortest path" title="DFS and shortest path" width="620" height="399" class="size-full wp-image-3401" srcset="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png 620w, /wp-content/uploads/2012/10/5.-DFS-and-shortest-path-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">DFS actually can find the longest path in some cases and can&#8217;t be used for finding shortest path!</figcaption></figure>
<p>In the image above using DFS the distance between 1 and 7 is 7 while practically there is an edge between them.</p>
<p>So BFS is the optimal algorithm for finding shortest paths in a graph. But there’s a catch! This algorithm works fine when we assume that all the edges are the same length. In the examples so far each edge has the value of 1. So N edges between s and i made the distance between them of a length N.</p>
<h2>Overview</h2>
<p>As we know in practice different edges can have different values. Exactly that was the case in weighted graphs. Going back to the road map example the distances between different cities are commonly evaluated in miles or kilometers. Of course we can associate any other meaningful value to this edges. This can be either time in hours to travel between cities, money for fuel or anything else.</p>
<figure id="attachment_3403" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png"><img src="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png" alt="Weighted Graphs in Practice" title="Weighted Graphs in Practice" width="620" height="399" class="size-full wp-image-3403" srcset="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png 620w, /wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In practice is more common to use weighted graphs than non-weighted graphs!</figcaption></figure>
<p>Now BFS can’t help us any more. Why? Because using non-equal values for the edges the triangle inequality is no longer true. Now the edge (the direct path) between A and B can be greater than the sum of the two edges (A, C) + (C, B)!</p>
<figure id="attachment_3404" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png"><img src="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png" alt="Triangle Inequality Problem" title="Triangle Inequality Problem" width="620" height="399" class="size-full wp-image-3404" srcset="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png 620w, /wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In a weighted graph the edges aren&#8217;t equal for our BFS algorithm so we can&#8217;t use it!</figcaption></figure>
<p>In other words, assuming the same abstraction with balls and wires the hanging wires can’t be discarded so easily.</p>
<figure id="attachment_3405" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png"><img src="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png" alt="Weighted Graph as Balls and Strings" title="Weighted Graph as Balls and Strings" width="620" height="399" class="size-full wp-image-3405" srcset="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png 620w, /wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">On weighted graphs BFS is no longer useful!</figcaption></figure>
<p>So now how can we solve this problem? A very dummy approach is to break apart each edge with dummy vertices in order to make BFS work again.</p>
<figure id="attachment_3406" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png"><img src="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png" alt="Breaking apart edges" title="Breaking apart edges" width="620" height="399" class="size-full wp-image-3406" srcset="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png 620w, /wp-content/uploads/2012/10/9.-Breaking-apart-edges-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Since the graph is weighted we can decompose its edges to more &#8220;dummy&#8221; edges!</figcaption></figure>
<p>However this approach has several weak points. The major one is that we’ll have to keep much more information, which means more memory usage, for even small graphs. This is done in case we break each edge on too many parts.</p>
<p>The solution of this problem was given by <a href="http://en.wikipedia.org/wiki/Edsger_W._Dijkstra" title="Edsger W. Dijkstra" target="_blank">Edsger Dijkstra</a> in 1956 and published in 1959. The only thing we should do now is to be sure that even discarding the triangle inequality we have the shortest paths. The first thing to do is to keep information for the distance from s to the parent (previous) node of i in the graph in order to calculate which distance is shorter.</p>
<p>In BFS we used a queue in order to walk through all the ancestors of a node. This was made consecutively. Thus for the graph G on the next image the order of enqueuing the ancestors of S was A, B, C.</p>
<figure id="attachment_3409" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png"><img src="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png" alt="Order of enqueuing" title="Order of enqueuing" width="620" height="399" class="size-full wp-image-3409" srcset="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png 620w, /wp-content/uploads/2012/10/10.-Order-of-enqueuing-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The order of enqueuing in BFS is consecutive &#8211; something that isn&#8217;t working for weighted graphs!</figcaption></figure>
<p>The Dijkstra’s algorithm make use of a priority queue, also know as a heap. This fact combined by the fact we keep info for the shortest path so far help us find shortest paths in a weighted graphs.</p>
<p>Why this works? To answer this question let’s see the next very basic example, assuming the graph G from the next image. As we can see the triangle inequality isn’t true.</p>
<figure id="attachment_3410" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/11.-Weighted-graph.png"><img src="/wp-content/uploads/2012/10/11.-Weighted-graph.png" alt="Weighted graph" title="Weighted graph" width="620" height="399" class="size-full wp-image-3410" srcset="/wp-content/uploads/2012/10/11.-Weighted-graph.png 620w, /wp-content/uploads/2012/10/11.-Weighted-graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A weighted graph that doesn&#8217;t follow the triangle inequality!</figcaption></figure>
<p>OK, we see that the path [S, B, A] is shorter than [S, A] although the edge (S, A) exists. How the Dijkstra algorithm overcomes this problem.</p>
<p>First we have no information about the distances (S, A) and (S, B), the only thing we know is that S is the starting point, its distance is 0 and its path so far is the empty set. So first we enqueue in a priority the distances from S to A and B.</p>
<figure id="attachment_3411" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png"><img src="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png" alt="Dijkstra Priority Queue" title="Dijkstra Priority Queue" width="620" height="399" class="size-full wp-image-3411" srcset="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png 620w, /wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The algorithm of Dijkstra make use of a priority queue!</figcaption></figure>
<p>Now we dequeue the minimum (first in the heap) element from the queue &#8211; the closest node to S, which is B. Then all the nodes adjacent to S in the queue are tested for adjacency to B, thus if we have already the distance between S and A now we can test if its longer than (S, B) + (B, A) &#8211; the triangle inequality!</p>
<p>So far we know that we must change a bit BFS to get the Dijkstra algorithm. The only thing to do is to keep info for each node for the path through its parent and to use a priority queue.</p>
<h2>Code</h2>
<p>Implementing this algorithms isn’t much more difficult than BFS, so here’s the code in <a href="/category/php/" title="PHP on Stoimen.com">PHP</a>. However this example make use of the standard php library SPL and the PriorityQueue data structure, but any developer can code <a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" title="Computer Algorithms: Heap and Heapsort">his own heap</a>.</p>
<p>Here&#8217;s the graph from the code:</p>
<figure id="attachment_3413" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/0.-Graph.png"><img src="/wp-content/uploads/2012/10/0.-Graph.png" alt="The Graph from the Code" title="The Graph from the Code" width="620" height="399" class="size-full wp-image-3413" srcset="/wp-content/uploads/2012/10/0.-Graph.png 620w, /wp-content/uploads/2012/10/0.-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The graph!</figcaption></figure>
<pre lang="PHP">
class vertex
{
    public $key         = null;
    public $visited     = 0;
    public $distance    = 1000000;  // infinite
    public $parent      = null;
    public $path        = null;
    
    public function __construct($key) 
    {
        $this->key  = $key;
    }
}

class PriorityQueue extends SplPriorityQueue
{
    public function compare($a, $b)
    {
        if ($a === $b) return 0;
        return $a > $b ? -1 : 1;
    }
}

$v0 = new vertex(0);
$v1 = new vertex(1);
$v2 = new vertex(2);
$v3 = new vertex(3);
$v4 = new vertex(4);
$v5 = new vertex(5);

$list0 = new SplDoublyLinkedList();
$list0->push(array('vertex' => $v1, 'distance' => 3));
$list0->push(array('vertex' => $v3, 'distance' => 1));
$list0->rewind();

$list1 = new SplDoublyLinkedList();
$list1->push(array('vertex' => $v0, 'distance' => 3));
$list1->push(array('vertex' => $v2, 'distance' => 7));
$list1->rewind();

$list2 = new SplDoublyLinkedList();
$list2->push(array('vertex' => $v1, 'distance' => 7));
$list2->push(array('vertex' => $v3, 'distance' => 8));
$list2->push(array('vertex' => $v4, 'distance' => 12));
$list2->rewind();

$list3 = new SplDoublyLinkedList();
$list3->push(array('vertex' => $v0, 'distance' => 1));
$list3->push(array('vertex' => $v2, 'distance' => 8));
$list3->rewind();

$list4 = new SplDoublyLinkedList();
$list4->push(array('vertex' => $v2, 'distance' => 12));
$list4->push(array('vertex' => $v5, 'distance' => 3));
$list4->rewind();

$list5 = new SplDoublyLinkedList();
$list5->push(array('vertex' => $v4, 'distance' => 3));
$list5->rewind();

$adjacencyList = array(
    $list0,
    $list1,
    $list2,
    $list3,
    $list4,
    $list5,
);

function calcShortestPaths(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = new PriorityQueue();
    
    // push the starting vertex into the queue
    $q->insert($start, 0);
    $q->rewind();
    
    // mark the distance to it 0
    $start->distance = 0;
    
    // the path to the starting vertex
    $start->path = array($start->key);
    
    while ($q->valid()) {
        $t = $q->extract();
        $t->visited = 1;
        
        $l = $adjLists[$t->key];
        while ($l->valid()) {
            $item = $l->current();
            
            if (!$item['vertex']->visited) {
                if ($item['vertex']->distance > $t->distance + $item['distance']) {
                    $item['vertex']->distance = $t->distance + $item['distance'];
                    $item['vertex']->parent = $t;
                }
                
                $item['vertex']->path = array_merge($t->path, array($item['vertex']->key));
                
                $q->insert($item["vertex"], $item["vertex"]->distance);
            }
            $l->next();
        }
        $q->recoverFromCorruption();
        $q->rewind();
    }
}

calcShortestPaths($v0, $adjacencyList);

// The path from node 0 to node 5
// [0, 1, 2, 4, 5]
echo '[' . implode(', ', $v5->path) . ']';
</pre>
<h2>Complexity</h2>
<p>The complexity of that code is based on the complexity of BFS with the main difference that we keep a priority queue. For BFS we knew that the complexity was O(|V| + |E|), while Dijkstra&#8217;s algorithm has running time of O((|V| + |E|).log(|V|)). That is quite natural since the heapsort&#8217;s complexity is O(n.log(n))!</p>
<h2>Application</h2>
<p>Since the basic BFS can&#8217;t help us for weighted graphs and there are plenty of problems designed with weighted graphs obviously Dijkstra&#8217;s algorithm can be very handy. The only thing we should be aware of is the positive values of the edges.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Shortest Path in a Graph</title>
		<link>/2012/10/08/computer-algorithms-shortest-path-in-a-graph/</link>
		<comments>/2012/10/08/computer-algorithms-shortest-path-in-a-graph/#respond</comments>
		<pubDate>Mon, 08 Oct 2012 13:39:55 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[breadth-first search algorithm]]></category>
		<category><![CDATA[breadth-first search will]]></category>
		<category><![CDATA[Distance]]></category>
		<category><![CDATA[Edge disjoint shortest pair algorithm]]></category>
		<category><![CDATA[faster and more efficient algorithm]]></category>
		<category><![CDATA[graph algorithm]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[handy algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[shortest path algorithm]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3369</guid>
		<description><![CDATA[Introduction Since with graphs we can represent real-life problems it’s almost clear why we would need an efficient algorithm that calculates the shortest path between two vertices. Getting back to our example of a road map we can use such an algorithm in order to find the shortest path between two cities. This example, of &#8230; <a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Shortest Path in a Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Since with graphs we can represent real-life problems it’s almost clear why we would need an efficient algorithm that calculates the shortest path between two vertices. Getting back to our example of a road map we can use such an algorithm in order to find the shortest path between two cities. This example, of course, is very basic indeed, but it can give us a clear example of where shortest path can be applied.</p>
<p>In the other hand, we can model an enormous field of real-life problems using graphs – not only road maps. As we already know, whenever we have relations between different abstract objects we can refer an efficient graph algorithm.</p>
<p>OK, so we need a shortest path algorithm, but before we proceed with the exact algorithm first we’ll need to answer some questions and give some definitions.</p>
<h2>Overview</h2>
<p>First we need a definition of the terms distance and path between two nodes. A path is considered to be the sequence of vertices (or edges if you wish) between two vertices i and j. Of course we assume that there might be no path between any to vertices in the graph! Also we assume that this definition relates both for directed and undirected graphs. After we have the definition of a path we can proceed by defining a “distance”, which is said to be the number of edges in the path between i and j.</p>
<p><figure id="attachment_3391" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-Path-and-Distance.png"><img src="/wp-content/uploads/2012/10/1.-Path-and-Distance.png" alt="Path and Distance" title="Path and Distance" width="620" height="399" class="size-full wp-image-3391" srcset="/wp-content/uploads/2012/10/1.-Path-and-Distance.png 620w, /wp-content/uploads/2012/10/1.-Path-and-Distance-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">First we need to define what&#8217;s a path and a distance between two vertices in order to continue searching for the shortest path!</figcaption></figure><span id="more-3369"></span></p>
<p>Using this terms, if there’s an edge between i and j, the path between them is [i, j], while the distance is 1. Of course, for an undirected graph (i, j) equals to (j, i) and the path [i, j] equals the path [j, i], but that isn’t true for directed graphs where the path [i, j] differs in general from [j, i].</p>
<figure id="attachment_3390" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-Rule-of-the-Triangle.png"><img src="/wp-content/uploads/2012/10/2.-Rule-of-the-Triangle.png" alt="Rule of the Triangle" title="Rule of the Triangle" width="620" height="399" class="size-full wp-image-3390" srcset="/wp-content/uploads/2012/10/2.-Rule-of-the-Triangle.png 620w, /wp-content/uploads/2012/10/2.-Rule-of-the-Triangle-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Although path (shortest path) is applicable for both directed and undirectd graphs, they depend in both cases of the graph type!</figcaption></figure>
<p>Here we talk about the path between two adjacent vertices, but we can go with the more general case of a path between two vertices that aren’t adjacent. </p>
<p>Now, getting back to the road map example, there might be many paths between city A and city B. </p>
<figure id="attachment_3389" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-Paths-Between-Cities.png"><img src="/wp-content/uploads/2012/10/3.-Paths-Between-Cities.png" alt="Paths Between Cities" title="Paths Between Cities" width="620" height="399" class="size-full wp-image-3389" srcset="/wp-content/uploads/2012/10/3.-Paths-Between-Cities.png 620w, /wp-content/uploads/2012/10/3.-Paths-Between-Cities-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">If we talk about paths between cities its pretty natural to talk about more than one &#8220;valid&#8221; path!</figcaption></figure>
<p>What we actually need to find is the shortest one. This can be very important, because we often want to get from A to B as quickly as possible using the shortest path.</p>
<figure id="attachment_3388" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/4.-Shortest-Path-Between-Cities.png"><img src="/wp-content/uploads/2012/10/4.-Shortest-Path-Between-Cities.png" alt="Shortest Path Between Cities" title="Shortest Path Between Cities" width="620" height="399" class="size-full wp-image-3388" srcset="/wp-content/uploads/2012/10/4.-Shortest-Path-Between-Cities.png 620w, /wp-content/uploads/2012/10/4.-Shortest-Path-Between-Cities-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The shortest path between two vertices is the path with lower distance compared to all other paths between the same points!</figcaption></figure>
<p>So first, what is a shortest path between i and j. Well, besides the strict definition, I’ll give a simplified one that might be clearer. The shortest path between i and j is such a path, which has the lowest distance compared to all other paths between i and j. </p>
<p>In our algorithm we will use breadth-first search. Why? That is because by using BFS by starting at a given point we expand our search consecutively starting with the closest vertices.</p>
<figure id="attachment_3387" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/5.-Shortest-Path-Canvas.png"><img src="/wp-content/uploads/2012/10/5.-Shortest-Path-Canvas.png" alt="BFS: Shortest Path Canvas" title="BFS: Shortest Path Canvas" width="620" height="399" class="size-full wp-image-3387" srcset="/wp-content/uploads/2012/10/5.-Shortest-Path-Canvas.png 620w, /wp-content/uploads/2012/10/5.-Shortest-Path-Canvas-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Breadth-first search can help us find the shortest paths between a given vertex (s) and all other reachable vertices!</figcaption></figure>
<p>Is breadth-first search enough and will it give us the correct answer – the shortest path between i and j. Actually breadth-first search will gives us even more – the shortest paths to each reachable vertex from a given starting point – the staring vertex.</p>
<p>Why this is correct? Well, because of the nature of the breadth-first search algorithm. As we already know BFS uses a queue in order to store the front of the expansion. Usually as an abstraction BFS colors the vertices in white, gray and black, where the white vertices are those that aren’t visited yet, the gray are in the queue and the black vertices are already visited.</p>
<figure id="attachment_3386" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/6.-White-Gray-Black.png"><img src="/wp-content/uploads/2012/10/6.-White-Gray-Black.png" alt="White, Gray, Black" title="White, Gray, Black" width="620" height="399" class="size-full wp-image-3386" srcset="/wp-content/uploads/2012/10/6.-White-Gray-Black.png 620w, /wp-content/uploads/2012/10/6.-White-Gray-Black-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">By putting a color to visited/unvisited and currently inspected vertices we can get a clearer impression on how breadth-first search works!</figcaption></figure>
<p>However how can be sure that BFS will give us the shortest paths to each vertex? To answer this question and to be sure that BFS will work for us we must take a closer look at the queue. Clearly by starting at a given point the algorithm is correct – the distance is 0.</p>
<p>Now the second step is to put into the queue all the vertices adjacent to s (where s is the starting point). Clearly this will give us the shortest paths to all adjacent vertices of s.</p>
<p>Continuing by induction we can assume that at level k we have all the shortest paths from s to all the vertices at the level k. It is clear the path between s and the vertices at level k is k, since we assume that each edge adds 1 to the path from s to i. Now by adding all the vertices adjacent (and not visited yet) to the paths of level k we get paths with length k+1 which is again the shortest paths from s to level k+1. </p>
<figure id="attachment_3385" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/7.-Shortest-Paths.png"><img src="/wp-content/uploads/2012/10/7.-Shortest-Paths.png" alt="Shortest Paths" title="Shortest Paths" width="620" height="399" class="size-full wp-image-3385" srcset="/wp-content/uploads/2012/10/7.-Shortest-Paths.png 620w, /wp-content/uploads/2012/10/7.-Shortest-Paths-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Finding the shortest paths using BFS can be proved by induction!</figcaption></figure>
<p>Actually we can talk about a tree built out of the graph by staring at s (which is the root of the tree).</p>
<figure id="attachment_3384" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/8.-Spanning-tree.png"><img src="/wp-content/uploads/2012/10/8.-Spanning-tree.png" alt="Spanning tree" title="Spanning tree" width="620" height="399" class="size-full wp-image-3384" srcset="/wp-content/uploads/2012/10/8.-Spanning-tree.png 620w, /wp-content/uploads/2012/10/8.-Spanning-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">BFS walks through the graph by constructing a virtual tree!</figcaption></figure>
<h2>Code</h2>
<p>OK, now we know that BFS will find us the shortest paths from s to all the reachable vertices from s. Here’s a simple PHP implementation, that makes use of the Standard PHP Library data structures. Of course, everyone can code and use his own implementation of lists in order to keep the information of the adjacency lists.</p>
<p>The important thing to note is that we keep an additional information in each vertex – the distance between it and s, which is initially infinite. First we go with the modification of BFS in order to find all the distances between s and the other vertices.</p>
<p>Here’s our graph:</p>
<figure id="attachment_3392" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/9.-Graph.png"><img src="/wp-content/uploads/2012/10/9.-Graph.png" alt="Graph" title="Graph" width="620" height="399" class="size-full wp-image-3392" srcset="/wp-content/uploads/2012/10/9.-Graph.png 620w, /wp-content/uploads/2012/10/9.-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The graph for the example!</figcaption></figure>
<pre lang="PHP">
class vertex
{
    public $key = null;
    public $color = 'white';
    public $distance = -1;  // infinite
    
    public function __construct($key) 
    {
        $this->key = $key;
    }
}

$v0 = new vertex(0);
$v1 = new vertex(1);
$v2 = new vertex(2);
$v3 = new vertex(3);
$v4 = new vertex(4);
$v5 = new vertex(5);

$list0 = new SplDoublyLinkedList();
$list0->push($v1);
$list0->push($v3);
$list0->rewind();

$list1 = new SplDoublyLinkedList();
$list1->push($v0);
$list1->push($v2);
$list1->rewind();

$list2 = new SplDoublyLinkedList();
$list2->push($v1);
$list2->push($v3);
$list2->push($v4);
$list2->rewind();

$list3 = new SplDoublyLinkedList();
$list3->push($v1);
$list3->push($v2);
$list3->rewind();

$list4 = new SplDoublyLinkedList();
$list4->push($v2);
$list4->push($v5);
$list4->rewind();

$list5 = new SplDoublyLinkedList();
$list5->push($v4);
$list5->rewind();

$adjacencyList = array(
    $list0,
    $list1,
    $list2,
    $list3,
    $list4,
    $list5,
);

function calcDistances(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = array();
    
    // push the starting vertex into the queue
    array_push($q, $start);
    
    // color it gray
    $start->color = 'gray';
    
    // mark the distance to it 0
    $start->distance = 0;
    
    while ($q) {
        // 1. pop from the queue
        $t = array_pop($q);
        
        // 2. foreach poped item find it's adjacent white vertices
        $l = $adjLists[$t->key];
        while ($l->valid()) {
            // 3. mark them gray, increment their length with one from their parent
            if ($l->current()->color == 'white') {
                $l->current()->color = 'gray';
                $l->current()->distance = $t->distance + 1;
                // 4. push them to the queue
                array_push($q, $l->current());
            }
            
            $l->next();
        }
    }
}

calcDistances($v0, $adjacencyList);

print_r($adjacencyList);
</pre>
<p>Now we can modify the algorithm even more and we add the path property of each vertex. Now each vertex will keep the path from s.</p>
<pre lang="PHP">
class vertex
{
    public $key         = null;
    public $color       = 'white';
    public $distance    = -1;  // infinite
    public $path        = null;
    
    public function __construct($key) 
    {
        $this->key  = $key;
    }
}

$v0 = new vertex(0);
$v1 = new vertex(1);
$v2 = new vertex(2);
$v3 = new vertex(3);
$v4 = new vertex(4);
$v5 = new vertex(5);

$list0 = new SplDoublyLinkedList();
$list0->push($v1);
$list0->push($v3);
$list0->rewind();

$list1 = new SplDoublyLinkedList();
$list1->push($v0);
$list1->push($v2);
$list1->rewind();

$list2 = new SplDoublyLinkedList();
$list2->push($v1);
$list2->push($v3);
$list2->push($v4);
$list2->rewind();

$list3 = new SplDoublyLinkedList();
$list3->push($v1);
$list3->push($v2);
$list3->rewind();

$list4 = new SplDoublyLinkedList();
$list4->push($v2);
$list4->push($v5);
$list4->rewind();

$list5 = new SplDoublyLinkedList();
$list5->push($v4);
$list5->rewind();

$adjacencyList = array(
    $list0,
    $list1,
    $list2,
    $list3,
    $list4,
    $list5,
);

function calcShortestPaths(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = array();
    
    // push the starting vertex into the queue
    array_push($q, $start);
    
    // color it gray
    $start->color = 'gray';
    
    // mark the distance to it 0
    $start->distance = 0;
    
    // the path to the starting vertex
    $start->path = new SplDoublyLinkedList();
    $start->path->push($start->key);
    
    while ($q) {
        // 1. pop from the queue
        $t = array_pop($q);
        
        // 2. foreach poped item find it's adjacent white vertices
        $l = $adjLists[$t->key];
        while ($l->valid()) {
            // 3. mark them gray, increment their length with one from their parent
            if ($l->current()->color == 'white') {
                $l->current()->color = 'gray';
                $l->current()->distance = $t->distance + 1;
                $l->current()->path = clone $t->path;
                $l->current()->path->push($l->current()->key);
                
                // 4. push them to the queue
                array_push($q, $l->current());
            }
            
            $l->next();
        }
    }
}

calcShortestPaths($v0, $adjacencyList);

print_r($adjacencyList);
</pre>
<h2>Complexity</h2>
<p>Clearly the complexity of enqueue and dequeue is O(V), while searching for adjacent vertices is O(E), thus the complexity of this algorithm is O(V + E)!</p>
<h2>Application</h2>
<p>Finding the shortest path between two nodes is obviousely a very handy algorithm. Applied almost everywhere graphs exists this algorithm is widely used. However there&#8217;s one very reasonable question. We&#8217;re searching for the shortest path between two vertices and we end with the shortest paths between a starting node an all other vertices? Why we need this &#8220;useless&#8221; information? Acutally the question should be: is there a faster and more efficient algorithm compared to this one. Well, we&#8217;ll see that!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/08/computer-algorithms-shortest-path-in-a-graph/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graph Best-First Search</title>
		<link>/2012/09/24/computer-algorithms-graph-best-first-search/</link>
		<comments>/2012/09/24/computer-algorithms-graph-best-first-search/#comments</comments>
		<pubDate>Mon, 24 Sep 2012 10:44:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Algebraic graph theory]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[graph traversal algorithms]]></category>
		<category><![CDATA[Hopcroft–Karp algorithm]]></category>
		<category><![CDATA[Matching]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Path decomposition]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[two algorithms]]></category>
		<category><![CDATA[typical greedy algorithm]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3347</guid>
		<description><![CDATA[Introduction So far we know how to implement graph depth-first and breadth-first search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal. In the examples so &#8230; <a href="/2012/09/24/computer-algorithms-graph-best-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Best-First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>So far we know how to implement graph <a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" title="Computer Algorithms: Graph Depth-First Search">depth-first</a> and <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" title="Computer Algorithms: Graph Breadth First Search">breadth-first</a> search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal.</p>
<p>In the examples so far we had an undirected, unweighted graph and we were using adjacency matrices to represent the graphs. By <a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" title="Computer Algorithms: Graphs and their Representation">using adjacency matrices</a> we store <strong>1</strong> in the A[i][j] if there’s an edge between vertex i and vertex j. Otherwise we put a <strong>0</strong>. However the value of <strong>1</strong> gives us only the information that we have an edge between two vertices, which is not always enough when designing graphs.</p>
<p>Indeed graphs can be weighted. Sometimes the path between two vertices can have a value. Thinking of a road map we know that distances between cities are represented in miles or kilometers. Thus often representing a road map as a graph, we don’t put just 1 between city A and city B, to say that there is a path between them, but also we put some meaningful information – let’s say the distance in miles between A and B. </p>
<p>Note that this value can be the distance in miles, but it can be something else, like the time in hours we’ve to walk between those two cities. In general this value is a function of A and B. So if we keep the distance between A and B we can say this function is F(A, B) = X, or distance(A, B) = X miles.</p>
<p>Of course in this particular example F(A, B) = F(B, A), but this isn’t always true in practice. We can have a directed graph where F(A, B) != F(B, A).</p>
<p>Here I talk about distance between two cities and it is the edge that brings some additional information. However sometimes we have to store the value of the vertices. Let&#8217;s say I&#8217;m playing a game (like chess) and each move brings me some additional benefit. So each move (vertex) can be evaluated with some particular value. Thus sometimes we don&#8217;t have a function of and edge like F(A, B), but function of the vertices, like F(A) and F(B).</p>
<p>In breadth-first search and depth-first search we just pick up a vertex and we consecutively walk through all its successors that haven’t been visited yet.</p>
<figure id="attachment_3357" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png"><img src="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png" alt="Walk Through an Unweithed Graph" title="Unweithed Graph Walkthrough" width="620" height="399" class="size-full wp-image-3357" srcset="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png 620w, /wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In order to walk through an unweithed graph using DFS, we chose consecutively each successor of node i!</figcaption></figure>
<p>So in DFS in particular we started from left to right in the array above. So the first node that has to be explored is vertex “1”.</p>
<pre lang="PHP">
0: [0, 1, 0, 0, 1, 1]
</pre>
<p>However sometimes, as I said above, we have weighted graphs, so the question is – is there any problem, regarding to the algorithm speed, if we go consecutively through all successors. The answer in general is yes, so we must modify a bit our code in order to continue not with the first but with the best matching successor. By best-matching we mean that the successor should match some criteria like – minimal or maximal value.<span id="more-3347"></span></p>
<h2>Overview</h2>
<p>In the following example we see that some of the successors of vertex 0 are very far from it, while others are closer. Thus 4 has the value of 5, while node 1’s value is 2 and 5 is 1.</p>
<figure id="attachment_3359" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png"><img src="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png" alt="DFS and Weighted Graph" title="DFS and Weighted Graph" width="620" height="399" class="size-full wp-image-3359" srcset="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png 620w, /wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Weithed graph brings us more information about the successors of a given vertex. Thus we have to chose carefully which one to get first in our path exploration!</figcaption></figure>
<pre lang="PHP">
0: [0, 2, 0, 0, 5, 1]
</pre>
<p>In this case if we’re searching for the shortest path between 1 and 3, although 1 and 4 are the first two successors in the adjacency matrix of the &#8220;start&#8221; vertex, we don&#8217;t choose them since there’s a better solution – going through node 5.</p>
<figure id="attachment_3360" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/3.-Best-First-Search.png"><img src="/wp-content/uploads/2012/09/3.-Best-First-Search.png" alt="Best-First Search" title="Best-First Search" width="620" height="399" class="size-full wp-image-3360" srcset="/wp-content/uploads/2012/09/3.-Best-First-Search.png 620w, /wp-content/uploads/2012/09/3.-Best-First-Search-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In best-first search we continue the path to the target through the best-matching successor!</figcaption></figure>
<h3>Problems</h3>
<p>The question is – are we sure that by choosing node 5, we’ll find the best path? Even more! Is there a path through node 5? As we see on the image below both cases are possible.</p>
<figure id="attachment_3361" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/4.-BFS-problems.png"><img src="/wp-content/uploads/2012/09/4.-BFS-problems.png" alt="BFS problems" title="BFS problems" width="620" height="399" class="size-full wp-image-3361" srcset="/wp-content/uploads/2012/09/4.-BFS-problems.png 620w, /wp-content/uploads/2012/09/4.-BFS-problems-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Somtimes best-first search doesn&#8217;t find the &#8220;best&#8221; (shortest/longest/cheapest) path to the target!</figcaption></figure>
<p>Practically best-first search is identical with depth-first search, with the main difference that we choose the best-matching successor instead of choosing the first matching successor. So we’re sure that we’re going through all the successors but in some particular order, different from DFS. Thus we know that if there’s a path we’ll find it.</p>
<p>However even if we find the path between A and B, we can’t be sure that there is not a better path. We only know that this path is the best so far. </p>
<p>Another question is – how can we find the best matching successor effectively. Well if we’re looking for the minimal or maximal value one possible solution is to sort the array of successors.</p>
<figure id="attachment_3363" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png"><img src="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png" alt="Using Priority Queues" title="Using Priority Queues" width="620" height="412" class="size-full wp-image-3363" srcset="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png 620w, /wp-content/uploads/2012/09/5.-Using-Priority-Queues-300x199.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The difference between depth-first and best-first is that we change the order of chosing the next successor!</figcaption></figure>
<pre lang="PHP">
0: [0 => 0, 1 => 2, 2 => 0, 3 => 0, 4 => 5, 5 => 1]
// sorted by value
0: [5 => 1, 1 => 2, 4 => 5, 0 => 0, 2 => 0, 3 => 1]
</pre>
<p>Another good approach will be to use priority queues or heaps.</p>
<p>Thus on every step we’ll get the best matching successor.</p>
<h2>Code</h2>
<p>In general best-first search uses the ground of depth-first search, so its implementation isn&#8217;t more difficult! The following PHP code snippet shows the very small difference between these two algorithms.</p>
<pre lang="PHP">
class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();
    
    public function __construct()
    {
        $this->_g = array(
            array(0, 2, 0, 0, 5, 1),
            array(1, 0, 3, 0, 0, 0),
            array(0, 2, 0, 8, 0, 0),
            array(0, 0, 3, 0, 5, 0),
            array(1, 0, 0, 8, 0, 1),
            array(1, 0, 0, 0, 5, 0),
        );
        
        $this->_len = count($this->_g);
        
        $this->_initVisited();
    }
    
    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }
    
    public function bestFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
    
        echo $vertex . "\n";
        
        asort($this->_g[$vertex]);
        
        foreach ($this->_g[$vertex] as $key => $v) {
            if ($v > 0 && !$this->_visited[$key]) {
                $this->bestFirst($key);
            }
        }
    }
}

$g = new Graph();
// 2 1 0 5 4 3
$g->bestFirst(2);
</pre>
<h2>Application</h2>
<p>Best-first search is a typical greedy algorithm. In its principles lies the main greedy approach of chosing the best possible solution so far. It is important to note that depth-first search and breadth-first search are the very basic graph walk through approaches, but they can be also widely extended in order to solve more complex problems.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/24/computer-algorithms-graph-best-first-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graph Depth-First Search</title>
		<link>/2012/09/17/computer-algorithms-graph-depth-first-search/</link>
		<comments>/2012/09/17/computer-algorithms-graph-depth-first-search/#comments</comments>
		<pubDate>Mon, 17 Sep 2012 10:52:59 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Connectivity]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[graph-walk algorithm]]></category>
		<category><![CDATA[In-place algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[specific algorithms]]></category>
		<category><![CDATA[two main algorithms]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3340</guid>
		<description><![CDATA[Introduction Along with breadth-first search, depth-first search is one of the two main methods to walk through a graph. This approach though is different. Breadth-first search (BFS) looks pretty much like starting from a vertex and expanding the searching process level by level. This means that first we get some information of all the successors &#8230; <a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Depth-First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Along with <a title="Computer Algorithms: Graph Breadth First Search" href="/2012/09/10/computer-algorithms-graph-breadth-first-search/">breadth-first search</a>, depth-first search is one of the two main methods to walk through a graph. This approach though is different. Breadth-first search (BFS) looks pretty much like starting from a vertex and expanding the searching process level by level. This means that first we get some information of all the successors of the given node and then we go further with the next level. In other words BFS is like a wave. Depth-first search is based on a different approach, which can be very useful in some specific algorithms.</p>
<figure id="attachment_3348" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png"><img class="size-full wp-image-3348" title="DFS vs. BFS" src="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png" alt="DFS vs. BFS" width="621" height="351" srcset="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png 621w, /wp-content/uploads/2012/09/1.-DFS-vs.-BFS-300x169.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Depth-first and breadth-first search are the two main ways to explore a graph!</figcaption></figure>
<p>Both methods can be useful in solving different tasks.<span id="more-3340"></span></p>
<h2>Overview</h2>
<p>Depth-first search is an algorithm that by given starting and target node, finds a path between them. We can use DFS also to walk through all the vertices of a graph, in case the graph is connected.</p>
<figure id="attachment_3350" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-DFS-explained.png"><img class="size-full wp-image-3350" title="DFS explained" src="/wp-content/uploads/2012/09/2.-DFS-explained.png" alt="DFS explained" width="621" height="351" srcset="/wp-content/uploads/2012/09/2.-DFS-explained.png 621w, /wp-content/uploads/2012/09/2.-DFS-explained-300x169.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">The algorithm frist goes in depth and then backtracks to all unvisited successors!</figcaption></figure>
<p>The whole idea of this algorithm is to go as far as possible from the given starting node searching for the target. In case we get to a node that has no successors, we get back (typically this is done recursively) and we continue with the last vertex that isn’t visited yet.</p>
<p>So basically we have 3 steps:</p>
<ol>
<li>Pick up a vertex that isn&#8217;t visited yet and mark it visited;</li>
<li>Go to its first non-visited successor and mark it visited;</li>
<li>If all the successors of the vertex are already visited or it doesn&#8217;t have successors &#8211; go back to its parent;</li>
</ol>
<h2>Code</h2>
<p>The following <a href="/category/php/" title="PHP on Stoimen.com">PHP</a> code implements the depth-first search. The key point is the recursion in the method depthFirst.</p>
<pre lang="PHP">
class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();
    
    public function __construct()
    {
        $this->_g = array(
            array(0, 1, 1, 0, 0, 0),
            array(1, 0, 0, 1, 0, 0),
            array(1, 0, 0, 1, 1, 1),
            array(0, 1, 1, 0, 1, 0),
            array(0, 0, 1, 1, 0, 1),
            array(0, 0, 1, 0, 1, 0),
        );
        
        $this->_len = count($this->_g);
        
        $this->_initVisited();
    }
    
    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }
    
    public function depthFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
    
        echo $vertex . "\n";
        
        for ($i = 0; $i < $this->_len; $i++) {
            if ($this->_g[$vertex][$i] == 1 && !$this->_visited[$i]) {
                $this->depthFirst($i);
            }
        }
    }
}

$g = new Graph();
// 2 0 1 3 4 5
$g->depthFirst(2);
</pre>
<h2>Complexity</h2>
<p>By using an adjacency matrix we need n<sup>2</sup> space for a graph with <strong>n</strong> vertices. We also use an additional array to mark visited vertices, which requires additional space of <strong>n</strong>! Thus the space complexity is O(n<sup>2</sup>).</p>
<p>When it comes to time complexity since we have a recursion and we try visiting all the vertices on each step, the worst-case time is yet again O(n<sup>2</sup>)!</p>
<h2>Application</h2>
<p>This graph-walk algorithm can be very useful when solving some specific tasks like finding the shortest/longest paths in a graph. Although <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" title="Computer Algorithms: Graph Breadth First Search">BFS</a> and DFS aren&#8217;t the only methods of walking through a graph, they are considered the two main algorithms of that kind. This is important in order to solve graph-based problems.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/17/computer-algorithms-graph-depth-first-search/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: How to Determine the Day of the Week</title>
		<link>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/</link>
		<comments>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 19:31:03 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Calculating the day of the week]]></category>
		<category><![CDATA[Calendars]]></category>
		<category><![CDATA[Chronology]]></category>
		<category><![CDATA[computer]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Doomsday rule]]></category>
		<category><![CDATA[February]]></category>
		<category><![CDATA[Gregorian calendar]]></category>
		<category><![CDATA[informatics]]></category>
		<category><![CDATA[Julian calendar]]></category>
		<category><![CDATA[Leap year]]></category>
		<category><![CDATA[month]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Units of time]]></category>
		<category><![CDATA[USD]]></category>
		<category><![CDATA[Year zero]]></category>

		<guid isPermaLink="false">/?p=3058</guid>
		<description><![CDATA[Introduction Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any &#8230; <a href="/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: How to Determine the Day of the Week</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any century.</p>
<p>We know that 2012 started at Sunday. After we know that it’s easy to determine what day is the 2nd of January. It should be Monday. But things get a little more complex if we try to guess some date distant from January the 1st. Indeed 1st of Jan was on Sunday, but what day is 9th of May the same year. This is far more difficult to say. Of course we can go with a brute force approach and count from 1/Jan till 9/May, but that is quite slow and error prone.</p>
<figure id="attachment_3079" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/FollowingDays.png"><img class="size-full wp-image-3079" title="Following Days" src="/wp-content/uploads/2012/04/FollowingDays.png" alt="Following Days" width="619" height="315" srcset="/wp-content/uploads/2012/04/FollowingDays.png 619w, /wp-content/uploads/2012/04/FollowingDays-300x152.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">If 1st of January is Sunday the most logical thing to happen is 2nd of January to be Monday</figcaption></figure>
<p>So what we’ll do if we have to code a program that answers this question. The most easier way is to use a library. Almost every major library has built-in functions that can answer what day is on a given date. Such are date() in PHP or getDate() in JavaScript. But the question remains. How these library functions know the answer and how can we code such library function if our library doesn’t support such functionality?</p>
<p>There must be some algorithm to help us.<span id="more-3058"></span></p>
<h2>Overview</h2>
<p>Because months has different number of days, and most of them aren’t divisible by 7 without a remainder, months begin on different days. Thus if January begins on Sunday, the month of February the same year will begin on Wednesday. Of course in common years February has 28 days, which fortunately is divisible by 7 and thus February and March both begin on the same day, which is great, but isn’t true for leap years.</p>
<h3>What Do We Know About the Calendar</h3>
<p>First thing to know is that each week has exactly 7 days. We know also that a common year has 365 days, while a leap year has one day more &#8211; 366. Most of the months has 30 or 31 days, but February has only 28 days in common years and 29 in leap years.</p>
<p>Because 365 mod 7 = 1 in a common year each year begins exactly on the next day of the preceding year. Thus if 2011 started on Saturday, 2012 starts on Sunday. And yet again that is because 2011 is not a leap year.</p>
<figure id="attachment_3081" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/SomeStatistics.png"><img class="size-full wp-image-3081" title="Some Statistics" src="/wp-content/uploads/2012/04/SomeStatistics.png" alt="Some Statistics" width="620" height="254" srcset="/wp-content/uploads/2012/04/SomeStatistics.png 620w, /wp-content/uploads/2012/04/SomeStatistics-300x122.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A week always has 7 days, while a year has different number of days depending on the fact whether it&#39;s a leap or not!</figcaption></figure>
<p>What else do we know? Because a week has exactly seven days only February (with its 28 days in a common year) is divisible by 7 (28 mod 7 = 0) and has exactly four weeks in it. Thus in a common year February and March start on a same day. Unfortunately that is not true about the other months.</p>
<p>All these things we know about the calendar are great, so we can make some conclusions. Although eleven of the months have either 30 or 31 days they don’t start on a same day, but some of the months do appear to start on a same day just because the number of days between them is divisible by 7 without a remainder.</p>
<p>Let’s take a look on some examples. For instance September has 30 days, as November, while October, which is in between them has 31 days. Thus 30+30+31 makes 91. Fortunately 91 mod 7 = 0. So for each year September and December start on the same day (as they are after February they don’t depend on leap years). The same thing occurs to April and July and the good news is that in leap years even January starts on the same day as April and July.</p>
<figure id="attachment_3082" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png"><img class="size-full wp-image-3082" title="Periods of Days Divisible by 7" src="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png" alt="Periods of Days Divisible by 7" width="623" height="508" srcset="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png 623w, /wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7-300x244.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">Not only the number of days in February is divisible by 7. The sum of days of April, May and June is also divisible by 7!</figcaption></figure>
<p>Now we know that there are some relations between months. Thus if we know somehow that 13th of April is Monday, we’ll be sure that 13th of July is also Monday. Let’s see now a summary of these observations.</p>
<figure id="attachment_3083" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3083" title="Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png" alt="Corresponding Months in a Common Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">In a common year some months correspond!</figcaption></figure>
<p>We can also refer the following diagram.</p>
<figure id="attachment_3086" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3086" title="Table of Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png" alt="Table of Corresponding Months in a Common Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">It&#39;s clearer to see the corresponding months in a table view!</figcaption></figure>
<p>For leap years there are other corresponding months. Let’s take a look at the following image.</p>
<figure id="attachment_3087" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3087" title="Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png" alt="Corresponding Months in a Leap Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Corresponding months in a leap year differs from corresponding months in a common year!</figcaption></figure>
<p>Another way to get the same information is the following table.</p>
<figure id="attachment_3088" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3088" title="Table of Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png" alt="Table of Corresponding Months in a Leap Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Table view is easier to remember!</figcaption></figure>
<p>We know also that leap years happen to occur once per four years. However if there is a common year like the year 2001, which will be the next year that is common and starts and corresponds exactly on 2001? Because of leap years we can have a year starting on one of the seven days of the week and to be either leap or common. This means just 14 combinations.</p>
<p>Following these observations we can refer the following table.</p>
<pre lang="PHP">1700–1799     4
1800–1899     2
1900–1999     0
2000–2099     6
2100–2199     4
2200–2299     2
2300–2399     0
2400–2499     6
2500–2599     4
2600–2699     2</pre>
<p>You can clearly see the pattern “6 4 2 0”</p>
<p>Here’s the month table.</p>
<pre lang="PHP">Month		Common  	Leap
January 	0  		6
February	3 		2
March		3		3
April		6		6
May		1		1
June		4		4
July		6		6
August  	2		2
September	5		5
October 	0		0
November	3		3
December	5		5</pre>
<p>Columns 2 and 3 differs only for January and February.</p>
<p>Clearly the day table is as follows.</p>
<pre lang="PHP">Sunday  	0
Monday  	1
Tuesday 	2
Wednesday	3
Thursday	4
Friday  	5
Saturday	6</pre>
<p>Now let’s go back to the algorithm.</p>
<p>Using these tables and applying a simple formula we can calculate what day was on some given date. Here are the steps of this algorithm.</p>
<ol>
<li>Get the number for the corresponding century from the centuries table;</li>
<li>Get the last two digits from the year;</li>
<li>Divide the number from step 2 by 4 and get it without the remainder;</li>
<li>Get the month number from the month table;</li>
<li>Sum the numbers from steps 1 to 4;</li>
<li>Divide it by 7 and take the remainder;</li>
<li>Find the result of step 6 in the days table;</li>
</ol>
<h2>Implementation</h2>
<p>First let&#8217;s take a look on a simple practical example of the example above and then the code. Let’s answer the question from the first paragraph of this post.</p>
<p>What day was on January 31st, 1883?</p>
<ol>
<li>Take a look at the centuries table: for 1800 &#8211; 1899 this is 2.</li>
<li>Get the last two digits from the year: 83.</li>
<li>Divide 83 by 4 without a remainder: 83/4 = 20</li>
<li>Get the month number from the month table: Jan = 0.</li>
<li>Sum the numbers from steps 1 to 4: 2 + 83 + 20 + 0 = 105.</li>
<li>Divide it by 7 and take the remainder: 105 mod 7 = 0</li>
<li>Find the result of step 6 in the days table: Sunday = 0.</li>
</ol>
<p>The following code in PHP do implements the algorithm above.</p>
<pre lang="PHP">
function get_century_code($century)
{
	// XVIII
	if (1700 <= $century &#038;&#038; $century <= 1799)
		return 4;
		
	// XIX
	if (1800 <= $century &#038;&#038; $century <= 1899)
		return 2;
		
	// XX
	if (1900 <= $century &#038;&#038; $century <= 1999)
		return 0;
		
	// XXI
	if (2000 <= $century &#038;&#038; $century <= 2099)
		return 6;
		
	// XXII
	if (2100 <= $century &#038;&#038; $century <= 2199)
		return 4;
		
	// XXIII
	if (2200 <= $century &#038;&#038; $century <= 2299)
		return 2;
		
	// XXIV
	if (2300 <= $century &#038;&#038; $century <= 2399)
		return 0;
		
	// XXV
	if (2400 <= $century &#038;&#038; $century <= 2499)
		return 6;
	
	// XXVI
	if (2500 <= $century &#038;&#038; $century <= 2599)
		return 4;
	
	// XXVII
	if (2600 <= $century &#038;&#038; $century <= 2699)
		return 2;
}

/**
 * Get the day of a given date
 * 
 * @param $date
 */
function get_day_from_date($date) 
{
	$months = array(
		1 => 0,		// January
		2 => 3,		// February
		3 => 3,		// March
		4 => 6,		// April
		5 => 1,		// May
		6 => 4,		// June
		7 => 6,		// July
		8 => 2,		// August
		9 => 5,		// September
		10 => 0,	// October
		11 => 3,	// November
		12 => 5,	// December
	);
	
	$days = array(
		0 => 'Sunday',
		1 => 'Monday',
		2 => 'Tuesday',
		3 => 'Wednesday',
		4 => 'Thursday',
		5 => 'Friday',
		6 => 'Saturday',
	);
	
	// calculate the date
	$dateParts = explode('-', $date);
	$century = substr($dateParts[2], 0, 2);
	$year = substr($dateParts[2], 2);
	
	// 1. Get the number for the corresponding century from the centuries table
	$a = get_century_code($dateParts[2]);

	// 2. Get the last two digits from the year
	$b = $year;
	
	// 3. Divide the number from step 2 by 4 and get it without the remainder
	$c = floor($year / 4);
	
	// 4. Get the month number from the month table
	$d = $months[$dateParts[1]];

	// 5. Sum the numbers from steps 1 to 4
	$e = $a + $b + $c + $d;
	
	// 6. Divide it by 7 and take the remainder
	$f = $e % 7;
	
	// 7. Find the result of step 6 in the days table
	return $days[$f];
}

// Sunday
echo get_day_from_date('31-1-1883');
</pre>
<h2>Application</h2>
<p>This algorithm can be applied in many different cases although most of the libraries has built-in functions that can do that. The only problem besides that is that there are much more efficient algorithms that don&#8217;t need additional space (tables) of data. However this algorithm isn&#8217;t difficult to implement and it gives a good outlook of some facts in the calendar.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Merge Sort</title>
		<link>/2012/03/05/computer-algorithms-merge-sort/</link>
		<comments>/2012/03/05/computer-algorithms-merge-sort/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 20:50:55 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Adaptive sort]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[comparison model sorting algorithm]]></category>
		<category><![CDATA[Divide and conquer algorithm]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[interative solution]]></category>
		<category><![CDATA[interative solutions]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[recursive solution]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Strand sort]]></category>
		<category><![CDATA[three algorithms]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=2847</guid>
		<description><![CDATA[Introduction Basically sorting algorithms can be divided into two main groups. Such based on comparisons and such that are not. I already posted about some of the algorithms of the first group. Insertion sort, bubble sort and Shell sort are based on the comparison model. The problem with these three algorithms is that their complexity &#8230; <a href="/2012/03/05/computer-algorithms-merge-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Merge Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Basically sorting algorithms can be divided into two main groups. Such based on comparisons and such that are not. I already posted about some of the algorithms of the first group. Insertion sort, bubble sort and Shell sort are based on the comparison model. The problem with these three algorithms is that their complexity is O(n<sup>2</sup>) so they are very slow. </p>
<p>So is it possible to sort a list of items by comparing their items faster than O(n<sup>2</sup>)? The answer is yes and here’s how we can do it.</p>
<p>The nature of those three algorithms mentioned above is that we almost compared each two items from initial list.</p>
<figure id="attachment_2860" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png"><img src="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png" alt="Insertion sort and bubble sort make too many comparisons, exactly what merge sort tries to overcome!" title="Principles of primitive sorting algorithms" width="620" class="size-full wp-image-2860" srcset="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png 640w, /wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms-300x89.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Insertion sort and bubble sort make too many comparisons, exactly what merge sort tries to overcome!</figcaption></figure>
<p>This, of course, is not the best approach and we don’t need to do that. Instead we can try to divide the list into smaller lists and then sort them. After sorting the smaller lists, which is supposed to be easier than sorting the entire initial list, we can try to merge the result into one sorted list. This technique is typically known as “divide and conquer”.</p>
<p>Normally if a problem is too difficult to solve, we can try to break it apart into smaller sub-sets of this problem and try to solve them. Then somehow we can merge the results of the solved problems. </p>
<p><figure id="attachment_2856" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Divideandconquer.png"><img src="/wp-content/uploads/2012/03/Divideandconquer.png" alt="If it&#039;s too difficult to sort a large list of items, we can break it apart into smaller sub-lists and try to sort them!" title="Divide and conquer" width="620" class="size-full wp-image-2856" srcset="/wp-content/uploads/2012/03/Divideandconquer.png 640w, /wp-content/uploads/2012/03/Divideandconquer-300x188.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">If it&#039;s too difficult to sort a large list of items, we can break it apart into smaller sub-lists and try to sort them!</figcaption></figure><br />
<span id="more-2847"></span></p>
<h2>Overview</h2>
<p>Merge sort is a comparison model sorting algorithm based on the “divide and conquer” principle. So far so good, so let’s say we have a very large list of data, which we want to sort. Obviously it will be better if we divide the list into two sub-lists with equal length and then sort them. If they remain too large, we can continue breaking them down until we get to something very easy to sort as shown on the diagram bellow.</p>
<figure id="attachment_2859" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Mergepartinmergesort.png"><img src="/wp-content/uploads/2012/03/Mergepartinmergesort.png" alt="Merge sort is a typical example of divide and conquer technique!" title="Merge part in merge sort" width="620" class="size-full wp-image-2859" srcset="/wp-content/uploads/2012/03/Mergepartinmergesort.png 624w, /wp-content/uploads/2012/03/Mergepartinmergesort-232x300.png 232w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-caption-text">Merge sort is a typical example of divide and conquer technique!</figcaption></figure>
<p>The thing is that on some step of the algorithm we have two sorted lists and the tricky part is to merge them. However this is not so difficult.<br />
We can start comparing the first items of the lists and than we can pop the smaller of them both and put it into a new list containing the merged (sorted) array.</p>
<h2>Implementation</h2>
<p>The good news is that this algorithm is fast, but not so difficult to implement and that sounds quite good from a developer’s point of view. Here’s the implementation in PHP. Note that every algorithm that follows the divide and conquer principles can be easily implemented in a recursive solution. However recursion can be bitter so you can go for a iterative solution. Typically recursion is &#8220;replaced&#8221; by additional memory space in iterative solutions. Here&#8217;s a recursive version of merge sort.</p>
<pre lang="PHP">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function merge_sort($arr)  
{  
	if (count($arr) <= 1) {
		return $arr;  
	}

	$left = array_slice($arr, 0, (int)(count($arr)/2));  
	$right = array_slice($arr, (int)(count($arr)/2));  
	
	$left = merge_sort($left);  
	$right = merge_sort($right);  
	
	$output = merge($left, $right);  

	return $output;  
}  
      
      
function merge($left, $right)  
{  
	$result = array();  

	while (count($left) > 0 && count($right) > 0) {  
		if ($left[0] <= $right[0]) {  
			array_push($result, array_shift($left));  
		} else {  
			array_push($result, array_shift($right));  
		}  
	}  
      
	array_splice($result, count($result), 0, $left);  
	array_splice($result, count($result), 0, $right);  

	return $result;  
}  

// 1, 2, 3, 4, 5, 6, 7, 8
$output = merge_sort($input);
</pre>
<h2>Complexity</h2>
<p>It’s great that the complexity of merge sort is O(n*log(n)) even in the worst case! Note that even quicksort’s complexity can be O(n<sup>2</sup>) in the worst case. So we can be sure that merge sort is very stable no matter the input.</p>
<figure id="attachment_2857" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/mergesortcomplexity.png"><img src="/wp-content/uploads/2012/03/mergesortcomplexity.png" alt="Merge sort complexity is O(n*log(n))" title="merge sort complexity" width="620" class="size-full wp-image-2857" srcset="/wp-content/uploads/2012/03/mergesortcomplexity.png 640w, /wp-content/uploads/2012/03/mergesortcomplexity-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Merge sort complexity is O(n*log(n))</figcaption></figure>
<figure id="attachment_2858" style="width: 481px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg"><img src="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg" alt="Merge sort complexity is O(n*log(n)) even in the worst case!" title="Sorting Algorithms Complexity" width="481" height="104" class="size-full wp-image-2858" srcset="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg 481w, /wp-content/uploads/2012/03/SortingAlgorithmsComplexity-300x64.jpg 300w" sizes="(max-width: 481px) 100vw, 481px" /></a><figcaption class="wp-caption-text">Merge sort complexity is O(n*log(n)) even in the worst case!</figcaption></figure>
<h2>Two reasons why merge sort is useful</h2>
<h3>1. Fast no matter the input</h3>
<p>Merge sort is a great sorting algorithm mainly because it’s very fast and stable. It’s complexity is the same even in the worst case and it is O(n*log(n)). Note that even quicksort's complexity is O(n<sup>2</sup>) in the worst case, which for n = 20 is about 4.6 times slower!</p>
<figure id="attachment_2861" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png"><img src="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png" alt="Merge sort is about 4.6 times faster than quicksort for n = 20!" title="mergesort vs. bubble sort for n = 20" width="620" class="size-full wp-image-2861" srcset="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png 640w, /wp-content/uploads/2012/03/mergesortvs.bubblesortforn20-300x120.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>2. Easy implementation</h3>
<p>Another cool reason is that merge sort is easy to implement. Indeed most of the developer consider something fast to be difficult to implement, but that's not the case of merge sort.</p>
<h2>Three reasons why merge sort is not useful</h2>
<h3>1. Slower than non-comparison based algorithms</h3>
<p>Merge sort is however based on the comparison model and as such can be slower than algorithms non-based on comparisons that can sort data in linear time. Of course, this depends on the input data, so we must be careful for the input.</p>
<h3>2. Difficult to implement for beginners</h3>
<p>Although I don’t think this can be the main reason why not to use merge sort some people say that it can be difficult to implement for beginners, especially the merge part of the algorithm.</p>
<h3>3. Slower than insertion and bubble sort for nearly sorted input</h3>
<p>Again it is very important to know the input data. Indeed if the input is nearly sorted the insertion sort or bubble sort can be faster. Note that in the best case insertion and bubble sort complexity is O(n), while merge sort's best case is O(n*log(n)).</p>
<p>As a conclusion I can say that merge sort is practically one of the best sorting algorithms because it's easy to implement and fast, so it must be considered by every developer!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/05/computer-algorithms-merge-sort/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Google Closure Compiler doesn&#8217;t work?!</title>
		<link>/2010/01/20/google-closure-compiler-doesnt-work/</link>
		<comments>/2010/01/20/google-closure-compiler-doesnt-work/#respond</comments>
		<pubDate>Wed, 20 Jan 2010 09:06:29 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Comparison of Java and C Sharp]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Computing platforms]]></category>
		<category><![CDATA[Cross-platform software]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Exception handling]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java platform]]></category>
		<category><![CDATA[Java programming language]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=911</guid>
		<description><![CDATA[What are these strange java errors? No, it works but maybe the problem is you current Java version. The Google Closure Compiler requires 1.6 and most commonly you&#8217;re runing on 1.5 therefore it produces errors. It was my problem when I tried to run the application. At that moment it produced these lines of errors: &#8230; <a href="/2010/01/20/google-closure-compiler-doesnt-work/" class="more-link">Continue reading <span class="screen-reader-text">Google Closure Compiler doesn&#8217;t work?!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/18/google-closure-compiler/" rel="bookmark" title="Google Closure Compiler?">Google Closure Compiler? </a></li>
<li><a href="/2011/01/21/google-analytics-for-nokia-and-mobiles/" rel="bookmark" title="Google Analytics for Nokia &#8230; and Mobiles">Google Analytics for Nokia &#8230; and Mobiles </a></li>
<li><a href="/2010/04/13/secure-localstorage-now-thats-a-good-question/" rel="bookmark" title="Secure localStorage? Now that&#8217;s a good question!">Secure localStorage? Now that&#8217;s a good question! </a></li>
<li><a href="/2011/01/18/download-images-with-php/" rel="bookmark" title="Download Images with PHP">Download Images with PHP </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>What are these strange java errors?</h2>
<p>No, it works but maybe the problem is you current Java version. The Google Closure Compiler requires 1.6 and most commonly you&#8217;re runing on 1.5 therefore it produces errors. It was my problem when I tried to run the application. At that moment it produced these lines of errors:</p>
<blockquote>
<pre>java -jar compiler.jar --help</pre>
</blockquote>
<blockquote><p>Exception in thread &#8220;main&#8221; java.lang.UnsupportedClassVersionError: Bad version number in .class file<br />
at java.lang.ClassLoader.defineClass1(Native Method)<br />
at java.lang.ClassLoader.defineClass(ClassLoader.java:676)<br />
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)<br />
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)<br />
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)<br />
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)<br />
at java.security.AccessController.doPrivileged(Native Method)<br />
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)<br />
at java.lang.ClassLoader.loadClass(ClassLoader.java:317)<br />
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)<br />
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)<br />
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)</p></blockquote>
<p>Just update or switch your current Java version to 1.6 and everything will be fine!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/18/google-closure-compiler/" rel="bookmark" title="Google Closure Compiler?">Google Closure Compiler? </a></li>
<li><a href="/2011/01/21/google-analytics-for-nokia-and-mobiles/" rel="bookmark" title="Google Analytics for Nokia &#8230; and Mobiles">Google Analytics for Nokia &#8230; and Mobiles </a></li>
<li><a href="/2010/04/13/secure-localstorage-now-thats-a-good-question/" rel="bookmark" title="Secure localStorage? Now that&#8217;s a good question!">Secure localStorage? Now that&#8217;s a good question! </a></li>
<li><a href="/2011/01/18/download-images-with-php/" rel="bookmark" title="Download Images with PHP">Download Images with PHP </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/01/20/google-closure-compiler-doesnt-work/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
