J.me

PHP code, searching combination of T9

T9, which stands for Text on 9 keys, is a patented[1] predictive text technology for mobile phones, originally developed by Tegic Communications, now part of Nuance Communications[2]. Read more on Wikipedia

This is usually used in mobile phones for predictive alphabet input. Each key have associated letters, such as 2 for ABC, 3 for DEF, and so on… This function allow you to search combination from entered number, for example, input 23 will return ad, ae, af, bd, be, bf, cd, ce and cf, in array.


Here we go…

$t9 = 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 cari_kombinasi($angka)
{
	global $t9;
	if (! is_numeric($angka))
		return false;
	$arr = str_split($angka);
	$total = 1;
	for($a = count($arr) - 1; $a >= 0; $a--)
	{
		$total *= count($t9[$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] .= $t9[$arr[$b]][$l];
			if ($j >= 0 && $c == ($t[$j] * ($k+1)) - 1 || $j < 0)
			{
				$k++;
				if ($l < count($t9[$arr[$b]]) - 1)
					$l++;
				else
					$l = 0;
			}
		}
	}
	return $ret;
}

function cari_kombinasi_str($string)
{
	global $t9;
	if (empty($string))
		return false;
	$arr = str_split(strtolower($string));
	foreach ($arr as $a)
	{
		foreach ($t9 as $key => $val)
		{
			$tmp = array_keys($val, $a);
			if ($tmp)
				$conv .= $key;
		}
	}
	return cari_kombinasi($conv);
}

How is this code work? Well, it is pretty simple… First it counts how many character from the input, place it on loop. Second it counts how many combination it will return, place it on another loop. Then it counts how many times of looping to change the character. For example if the input is 393, then the first character will change every 12 times, the second character will change every 3 times and the third character will change in every loop, it counts from the back of input. This way, it will return 36 combination, nicely sorted… (do not need to call sort() anymore) 🙂 Well, maybe there is better way, but I think this is not a bad way either… 😉

The cari_kombinasi_str() function is just the same as cari_kombinasi, except that it accepts string than integer. So if you input “eye”, it is the same as input 393 on cari_kombinasi() function.

Well, hope it is useful… (it might not though :))

Tags:

2 comments | Leave a comment

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.