Pages

Search This Blog

Saturday 3 May 2014

Implementation Of Levenshtein Distance Algorithm in PHP

<?php

/*
 *
 * @Author: Zuhair Mirza
 * @Implementation Of Levenshtein Distance Algorithm (Edit Distance) in PHP
 * @Date : 04-May-2013
 *
 */

$s1 = "POLYNOMIAL";
$s2 = "EXPONENTIAL";

LevenshteinDistance($s1, $s2);


function LevenshteinDistance($s, $t) {
    $m = strlen($s);
    $n = strlen($t);

    for ($i = 0; $i <= $m; $i++)
        $d[$i][0] = $i;
    for ($j = 0; $j <= $n; $j++)
        $d[0][$j] = $j;

    for ($i = 1; $i <= $m; $i++) {
        for ($j = 1; $j <= $n; $j++) {

            $c = ($s[$i - 1] == $t[$j - 1]) ? 0 : 1;
            $d[$i][$j] = min($d[$i - 1][$j] + 1, $d[$i][$j - 1] + 1, $d[$i - 1][$j - 1] + $c);
        }
    }

    printMatrix($d, $s, $t);

    return $d[$m][$n];
}

function flip_row_col_array($array) {
    $out = array();
    foreach ($array as $rowkey => $row) {
        foreach ($row as $colkey => $col) {
            $out[$colkey][$rowkey] = $col;
        }
    }
    return $out;
}

function printMatrix($d, $str1, $str2) {

    $array = flip_row_col_array($d);
    echo "<table border = '1'>";
    echo "<tr>";
    echo "<td>";
    echo "</td>";
    echo "<td colspan=11>";
    echo $str1;
    echo "</td>";
    echo "</tr>";

    $str2 = str_split($str2);

    $count = 0;

    foreach ($array as $j => $value) {

        echo "<tr>";

        foreach ($value as $i => $node) {

            if ($i == 0):

                if ($count == 0):
                    echo "<td>";
                    echo "</td>";
                else:
                    echo "<td>";
                    echo $str2[$j - 1];
                    echo "</td>";

                endif;
                $count++;
            endif;

            echo "<td>";
            echo $node;
            echo "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
}

?>

No comments:

Post a Comment