Monday, June 18, 2012

Random Image Display

Many times we get bored without any reason.. if this is one of those moments then don't worry, coding will make the moment a little bit lighter;

We'll create a webpage that'll display a random image on each visit(refresh) to the page. PHP will be the language in which we'll create the webpage.

First of all, the RandomImage class,

class RandomImage {
    private $ImageDir;
    private $FileList;
   
    /* this is list of extension which will be allowed to display as an image */
    private $FilterList = array("jpg", "jpeg", "gif", "png");
   
    /* constructor */
    public function __construct($initDir) {
        $this->ImageDir = $initDir;
        $this->FileList = array();
    }
   
    /* function to filter out files based on extension */
    private function IsFileOkToShow($file){
        $isOk = false;
        /* check if file extension is not in the filter list */
        $matched = false;
        $fileExt = pathinfo($file, PATHINFO_EXTENSION);
        foreach ((array)$this->FilterList as $ext) {
            if(strcasecmp($fileExt, $ext) == 0) {
                $matched = true;
                break;
            }
        }
        if($matched) {
            $isOk = true;
        }
   
        return $isOk;
    }
   
    /* this function will scan through all the directories(in recursive manner)
     * and build the list of files in all directories.
     */
    private function buildImageList($dir) {
        if($handle = opendir($dir)) {
            while(false !== ($entry = readdir($handle))) {
                if($entry == '.' || $entry == '..') {
                    continue;
                }
                $fullPath = $dir.'/'.$entry;
                if(is_dir($fullPath)) {
                    $this->buildImageList($fullPath);
                } else {
                    if($this->IsFileOkToShow($fullPath)) {
                        array_push($this->FileList, $fullPath);
                    }
                }
            }
            closedir($handle);
        }
    }
   
    /* public function to return a random file */
    public function Get() {
        $this->buildImageList($this->ImageDir);
        srand((float)microtime()*1000000);
        $fileCount = count($this->FileList);
        if($fileCount > 0) {
            $randomIndex = rand(0, $fileCount -1);
            return $this->FileList[$randomIndex];
        } else {
            return "foo!";
        }
    }
}

This class is very simple and it has only one public function Get(). Calling the Get() function on an object of this class will scan through the directory and return a random file from it.

Upon receiving the filename, we'll pass this file to 'src' attribute of <img> tag, in order to display it.

<!--  html code to display the image -->
<html>
<head><title>Ignorance is bliss!</title></head>
<body>
<?php
    $image = new RandomImage("PATH_TO_IMAGE_FOLDER");
?>
    <img src="<?php echo $image->Get();?>">
<?php
?>
</body>
</html>

Thats all!
Download the attached source code and start clicking on refresh button!

Sunday, January 22, 2012

Re-build a Binary Tree from post-order and pre-order traverse

This is a well known problem, if we have two traversals of a binary tree, like post-order and pre-order etc.
we have to build a binary tree from these. Here is an example with post-order and pre-order case.


import java.util.Arrays;
import java.util.List;

public class ReConstructBTree {

/**
* @param args
*/
public static void main(String[] args) {

String[] pre = "I Q J H L E M V O T S B R G Y Z K C A & F P N U D W X".split("\\s");
String[] post = "H E M L J V Q S G Y R Z B T C P U D N F W & X A K O I".split("\\s");

List preList = Arrays.asList(pre);
List postList = Arrays.asList(post);

BTree tree = reBuildTree(preList, postList);

tree.inOrder(tree); //print in-order
System.out.println();
tree.postOrder(tree);//print post order to re-check
System.out.println();
tree.preOrder(tree);//print pre order to re-check
}

private static BTree reBuildTree(List preList, List postList) {
BTree tree = null;

if(preList.size() != 0 && postList.size() != 0) {
tree = new BTree();
String val = preList.get(0);
tree.val = val;

if(preList.size() > 1 && postList.size() > 1) {
int postOrderPos = postList.indexOf(preList.get(1));
int preOrderPos = preList.indexOf(postList.get(postList.size()-2));

//find the two sub set of the list from pre-order
List leftPreOrder = preList.subList(1, preOrderPos);
List rightPreOrder = preList.subList(preOrderPos, preList.size());

//find the two sub set of the list from post-order
List leftPostOrder = postList.subList(0, postOrderPos+1);
List rightPostOrder = postList.subList(postOrderPos+1, postList.size()-1);

tree.left = reBuildTree(leftPreOrder, leftPostOrder);
tree.right = reBuildTree(rightPreOrder, rightPostOrder);
}
}

return tree;
}

static class BTree {
String val;
BTree left;
BTree right;

void inOrder(BTree tree) {
if(tree.left != null)
inOrder(tree.left);
System.out.print(tree.val+" ");
if(tree.right != null)
inOrder(tree.right);
}

void preOrder(BTree tree) {
System.out.print(tree.val+" ");
if(tree.left != null)
preOrder(tree.left);
if(tree.right != null)
preOrder(tree.right);
}

void postOrder(BTree tree) {
if(tree.left != null)
postOrder(tree.left);
if(tree.right != null)
postOrder(tree.right);
System.out.print(tree.val+" ");
}

}
}