phptriet9

PHP T9 Dictionary Implementation using Trie


I want simplified implementation of T9 input method for mobile in PHP i.e. either using Trie or any other simple and best possible solution.

Any help will be highly appreciated.


Solution

  • It might not that efficient and there might be some better solution to your problem and its got some limitations as well e.g. if you enter number more than 15 digits it might not work properly. But I just tried to share my thoughts without using Tries it might gives you some idea. Just try and share your experience.

    <?php
    
    $T9Array = array(
        2 => array('a', 'b', 'c'),
        3 => array('d', 'e', 'f'),
        4 => array('g', 'h', 'i'),
        5 => array('j', 'k', 'l'),
        6 => array('m', 'n', 'o'),
        7 => array('p', 'q', 'r', 's'),
        8 => array('t', 'u', 'v'),
        9 => array('w', 'x', 'y', 'z')
    );
    
    function search_combination($input)
    {
        global $T9Array;
        if (! is_numeric($input))
            return false;
        $arr = str_split($input);
        $total = 1;
        for($a = count($arr) - 1; $a >= 0; $a--)
        {
            $total *= count($T9Array[$arr[$a]]);
            $t[$a] = $total;
        }
        sort($t);
        for ($b = 0; $b < count($arr); $b++)
        {
            $k = $l = 0;
            $j = count($arr) - ($b + 2);
            for ($c = 0; $c < $total; $c++)
            {
                $ret[$c] .= $T9Array[$arr[$b]][$l];
                if ($j >= 0 && $c == ($t[$j] * ($k+1)) - 1 || $j < 0)
                {
                    $k++;
                    if ($l < count($T9Array[$arr[$b]]) - 1)
                        $l++;
                    else
                        $l = 0;
                }
            }
        }
        return $ret;
    }
    
    function search_combination_str($string)
    {
        global $T9Array;
        if (empty($string))
            return false;
        $arr = str_split(strtolower($string));
        foreach ($arr as $a)
        {
            foreach ($T9Array as $key => $val)
            {
                $tmp = array_keys($val, $a);
                if ($tmp)
                    $conv .= $key;
            }
        }
        return search_combination($conv);
    }
    
    ?>