Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Created January 18, 2013 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheSavior/4561325 to your computer and use it in GitHub Desktop.
Save TheSavior/4561325 to your computer and use it in GitHub Desktop.
Check if the edit distance between two words is 1
<?php
/*
d = ['cat', 'cats', 'bat', 'beetle']
similar(q, d):
....
returns all words from d with edit distance 1
similar('cat', d) --> ['cat', 'cats', 'bat']
replace any letter in q
add a letter anywhere in q
drop any letter in q
'cat' -- 26 * 3 + 26 * 4 + 3
*/
// str2 is always longer
function dist_is_one($str1, $str2) {
$diff = abs(strlen($str1) - strlen($str2));
if ($diff > 1){
return false;
}
// assuming str2 is the longer one
for ($i = 0; $i < strlen($str1); $i++)
{
if ($str1[$i] != $str2[$i])
{
// cat, bat
// try a replace
$newStr = $str1; // TODO: Does this make a copy?
$newStr[$i] = $str2[$i];
if ($newStr == $str2)
return true;
// Insertion
// at, bat -> bt, bat ct cat
$newStr = $str1;
$newStr = substr($newStr, 0, $i).$str2[$i].substr($newStr, $i);
if ($newStr == $str2)
return true;
return false;
}
}
return true;
}
print_p(dist_is_one('ct', 'cat'));
print_p(dist_is_one('bat', 'cat'));
print_p(dist_is_one('adf', 'cat'));
print_p(dist_is_one('bdt', 'cat'));
print_p(dist_is_one('baaale', 'beetle'));
echo "<br />";
print_p(dist_is_one('', 'c'));
print_p(dist_is_one('', 'lol'));
print_p(dist_is_one('', ''));
print_p(dist_is_one('a', 'a'));
function print_p($ele) {
print var_dump($ele) ."<br />";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment