Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
janiceshiu committed Sep 11, 2017
0 parents commit be39343
Show file tree
Hide file tree
Showing 10 changed files with 145,909 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
words_with_prefix.txt
misspelled_words.txt
1 change: 1 addition & 0 deletions .ruby-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2.4.1
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## Ruby implementation of a trie that stores a dictionary
* The dictionary can be used to spellcheck words and to suggest words that begin with a particular prefix
* Associated [presentation](https://docs.google.com/presentation/d/1Zg0H-cHZjt-VvDdVxR1zdb1WsC3dfgkVVe_eXnP0uyM/edit?usp=sharing)

### Dictionary format
* each word is on a separate line
* no empty lines
* character set: uppercase and lowercase English alphabet, single apostrophe

### Format of text to be spellchecked
* Multiple words in a line
* Has empty lines
* character set: uppercase and lowercase English alphabet, single apostrophe, some punctuation marks

### Usage
* To spellcheck only: `./run`
* To spellcheck and find words with a certain prefix: `./run $PREFIX` (eg: `./run super`)
* Misspelled words are in `misspelled_words.txt`
* Words that start with the given prefix are in `words_with_prefix.txt`
* Total number of misspelled words and words that start with a given prefix are printed to the terminal
* Time taken is benchmarked with ruby's `benchmark` gem

### Notes
* `SpellChecker.new('large.txt').spellcheck_lines('sonnets.txt')`
* If needed, swap out `large.txt` for another dictionary and/or `sonnets.txt` for another text file
48 changes: 48 additions & 0 deletions dictionary.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Dictionary
attr_reader :root

def initialize(file)
@root = Node.new
@cursor = @root
@counter = 0
add_words(file)
end

def add_words(file)
IO.foreach(file) do |word|
add_word(word.chomp)
@counter += 1
end
puts("Added #{@counter} words into the dictionary")
end

private
def add_word(word)
set_cursor_to_root

word.downcase.each_char do |char|
if @cursor.children.nil?
@cursor.children = Array.new(27)
@cursor.children[get_dict_index(char)] = Node.new
elsif @cursor.children[get_dict_index(char)].nil?
@cursor.children[get_dict_index(char)] = Node.new
end
move_cursor_to_next_node(char)
end

@cursor.is_word = true
end

def get_dict_index(char)
return 26 if char == "'"
char.ord - 97
end

def set_cursor_to_root
@cursor = @root
end

def move_cursor_to_next_node(char)
@cursor = @cursor.children[get_dict_index(char)]
end
end
Loading

0 comments on commit be39343

Please sign in to comment.