Assignment 13
Trie
by Kristy Bond
HTML
<input type="button" value="Add to dictionary" onclick="addToDictionary()" />
<input type="textbox" value="" id="word" />
<input type="button" value="Spellcheck" onclick="spellcheck()"/>
<p id="output"></p>
JavaScript
var structure = Trie {
integer words;
integer prefixes;
reference edges[26];
}
function initialize(vertex) {
addWord(vertex, word);
integer countPrefixes(vertex, prefix);
integer countWords(vertex, word);
}
function initialize(vertex) {
vertex.words=0;
vertex.prefixes=0;
for i=0 to 26;
edges[i]=NoEdge;
}
function addWord(vertex, word) {
if isEmpty(word) {
vertex.words=vertex.words+1; }
else {
vertex.prefixes=vertex.prefixes+1;
k=firstCharacter(word);
if (notExists(edges[k])); {
edges[k]=createEdge();
initialize(edges[k]);
cutLeftmostCharacter(word);
addWord(edges[k], word); }
}
}
function countWords(vertex, word) {
k=firstCharacter(word);
if {isEmpty(word);
return vertex.words;}
else if {notExists(edges[k])
return 0;}
else {
cutLeftmostCharacter(word);
return countWords(edges[k], word);}
}
function countPrefixes(vertex, prefix) {
var k=firstCharacter(prefix);
if isEmpty(word) {
return vertex.prefixes; }
else if {notExists(edges[k]);
return 0; }
else {
cutLeftmostCharacter(prefix);
return countWords(edges[k], prefix); }
}
function countWords(vertex, word, missingLetters) {
var k=firstCharacter(word);
if isEmpty(word) {
return vertex.word; }
else if {notExists(edges[k]) and missingLetters=0;
return 0;}
else if {notExists(edges[k]);
cutLeftmostCharacter(word);
return countWords(vertex, word, missingLetters-1); }
//Here we cut a character but we don't go lower in the tree
else
// We are adding the two possibilities: the first
//character has been deleted plus the first character is present
{r=countWords(vertex, word, missingLetters-1);
cutLeftmostCharacter(word);
r=r+countWords(edges[k], word, missingLetters);
return r; }
...