Recently a friend of mine asked me to help out on a trivial problem of building and printing an N-Ary Tree in PHP. I have posted this solution for a quick reference.
<?php
//Data (Generally fetched from DB)
$arr=array(
array("id" =>1, "parent_id" =>0, "name" =>"India"),
array("id" =>2, "parent_id" =>1, "name" =>"North"),
array("id" =>3, "parent_id" =>1, "name" =>"East"),
array("id" =>4, "parent_id" =>1, "name" =>"South"),
array("id" =>5, "parent_id" =>1, "name" =>"West"),
array("id" =>6, "parent_id" =>2, "name" =>"Delhi"),
array("id" =>7, "parent_id" =>3, "name" =>"Bihar"),
array("id" =>8, "parent_id" =>2, "name" =>"Hariyana"),
array("id" =>9, "parent_id" =>5, "name" =>"Goa"),
array("id" =>10, "parent_id" =>4 , "name" =>"Andhra Pradesh"),
array("id" =>11, "parent_id" =>3 , "name" =>"Jharkhand"),
array("id" =>12, "parent_id" =>5 , "name" =>"Gujrat"),
array("id" =>13, "parent_id" =>4 , "name" =>"Karnataka")
);
//tree construction algo
function buildTree(&$elements, $parent_id=0) {
$branch = array();
foreach($elements as $node) {
if($node['parent_id']==$parent_id) {
$children = buildTree(&$elements, $node['id']);
if($children) {
$node['children'] = $children;
}
$branch[] = $node;
}
}
return $branch;
}
//print tree algo
function printTree($tree) {
foreach($tree as $node) {
echo "<li><a href='#'>".$node['name']."</a>";
if(isset($node['children'])) {
echo "<ul>";
printTree($node['children']);
echo "</ul>";
}
echo "</li>";
}
}
$tree = buildTree($arr);
?>
<!DOCTYPE html>
<html>
<head>
<title>Printing a Tree in PHP</title>
</head>
<body>
<ul>
<?php echo printTree($tree); ?>
</ul>
</body>
</html>
Output:
Problem:
Split an integer into an array without converting it into a string. The order of integers should be properly maintained. e.g: for an integer 123, the array should be like [1, 2, 3].
(I heard about this problem from one of my friend, this question was asked to him in an interview. Here is my solution in JavaScript. I have taken the liberty to assume the numbers will be of base 10 for now.)
Solution:
var test = 123 ,temp = 0 ,arr = []; while( test !== 0){ temp = test % 10; arr.unshift(temp); test = Math.floor(test/10); } console.log(arr);
output:
[1, 2, 3]
Small and sweet
Dough Crockford on Yahoo!
(a different talk on a different subject)
This is the Cognizant technologies building in Bagamane Tech Park (Bangalore), which is just besides Yahoo!.
Peace@3rd floor breakout area (Yahoo BTP building) (Taken with instagram)
Cafeteria@7 (Taken with instagram)
Early bird (Taken with instagram)
Prerequisite:
You should be using any Linux / Unix terminal to accomplish this.
Step 1: Connect to the remote Linux system using SSH
$> ssh -Y username@hostname
password: *******
Step 2: Launch an application
$> firefox
You will see the firefox browser pops up.