Lets say you have an array that contains a number of strings (perhaps char * a[100]). Each string is a word from the dictionary. Your task, described in high-level terms, is to devise a way to determine and display all of the anagrams within the array (two words are anagrams if they contain the same characters; for example, 'tales' and 'slate' are anagrams.)
You are expect to create a function printAnagrams( listOfStrings[] )
Input Array['abroad', 'aces', 'about', 'aboard', 'case']
Output:
abroad, aboard
aces, case
Solution:
<?php
$listOfStrings = array('abroad', 'aces', 'about', 'aboard', 'case');
printAnagrams($listOfStrings);
function printAnagrams($listOfStrings)
{
$numOfStrings = count($listOfStrings);
for($i=0;$i < $numOfStrings; $i++)
{
$sortedString = sortString($listOfStrings[$i]);
for($j=$i+1; $j< $numOfStrings; $j++)
{
$nextSortedString = sortString($listOfStrings[$j]);
//if sorted strings match they are anagrams
//identity operator to avoid matching between false and 0
if(strcmp($sortedString, $nextSortedString) === 0)
{
echo "\nAnagrams: ".$listOfStrings[$i]." , ".$listOfStrings[$j];
}
}
}
}
function sortString($stringValue)
{
$stringToArray = str_split($stringValue);
sort($stringToArray);
$sortedString = implode('',$stringToArray);
return $sortedString;
}
?>
You are expect to create a function printAnagrams( listOfStrings[] )
Input Array['abroad', 'aces', 'about', 'aboard', 'case']
Output:
abroad, aboard
aces, case
Solution:
<?php
$listOfStrings = array('abroad', 'aces', 'about', 'aboard', 'case');
printAnagrams($listOfStrings);
function printAnagrams($listOfStrings)
{
$numOfStrings = count($listOfStrings);
for($i=0;$i < $numOfStrings; $i++)
{
$sortedString = sortString($listOfStrings[$i]);
for($j=$i+1; $j< $numOfStrings; $j++)
{
$nextSortedString = sortString($listOfStrings[$j]);
//if sorted strings match they are anagrams
//identity operator to avoid matching between false and 0
if(strcmp($sortedString, $nextSortedString) === 0)
{
echo "\nAnagrams: ".$listOfStrings[$i]." , ".$listOfStrings[$j];
}
}
}
}
function sortString($stringValue)
{
$stringToArray = str_split($stringValue);
sort($stringToArray);
$sortedString = implode('',$stringToArray);
return $sortedString;
}
?>
No comments:
Post a Comment