Purpose
The purpose of this script is to determine if two words represent an anagram. Over the decades of programming I've never needed to solve such a task but I was asked about it so I provide one approach (using javascript) below.
Determine if Words are an Anagram Question (and answer):
Determine if the two string words "listen" and "silent" are an anagram (each word contains exactly all the letters of the other word).
For reference, the value returned should be: true
Function Logic Output:
Full Working Code You Can Copy:
<html>
<head>
<script language="javascript" type="text/javascript">
function wordSort(sequence) {
var wordArray = [];
var sequenceModified = "";
/* Convert string to an array of characters and sort it */
for (var s = 0; s < sequence.length; s++) {
wordArray.push(sequence.charAt(s));
}
wordArray.sort();
/* Convert array back into a string */
for (var m = 0; m < wordArray.length; m++) {
var letter = wordArray[m];
sequenceModified = sequenceModified.concat(letter);
}
return(sequenceModified);
}
function determineIfAnagram(sequenceA, sequenceB) {
var result = false;
var word1 = sequenceA.toLowerCase();
var word2 = sequenceB.toLowerCase();
if (word1.length == word2.length) {
word1 = wordSort(word1);
word2 = wordSort(word2);
if (word1 == word2) {
result = true;
}
}
return(result);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = determineIfAnagram("listen", "silent");'>
Determine if the two string words "listen" and "silent" are an anagram (each word contains exactly all the letters of the other word).<br />
<span style="font-size:9pt">For reference, the value returned should be: true</span>
<br /><br />
<strong>Function Logic Output:</strong><br />
<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>