The scenario is well defined already:
- the user types in a string in a field restricted to a dictionary
- we know how to calculate the edit distance between every string in our dictionary and the user input
- so we bundle up a word with its score and define a sorting rule
public class SpellSuggester { private List<Word> dictionary; public SpellSuggester(...) { // load the dictionary however you prefer } public List<Word> getSimilarWords(String wordToSearch, int limit) { // 1. compute the score for (Word word : dictionary) { word.setScore(spellChecking.levenshteinDistance(word.getWord(), wordToSearch)); } // 2. sort Collections.sort(dictionary, new WordComparator()); // 3. extract the first 'limit' entries (if limit == 0 returns the whole list) if (limit<=0) { return dictionary; } else { return dictionary.subList(0, limit); } } }
Pretty simple isn't it?
Nessun commento:
Posta un commento