Skip to content

Instantly share code, notes, and snippets.

@arxenix
Created August 31, 2013 00:08
Show Gist options
  • Save arxenix/6395396 to your computer and use it in GitHub Desktop.
Save arxenix/6395396 to your computer and use it in GitHub Desktop.
Bukkit FuzzySearch for commands. Easily fuzzy search for the correct command! Easy to use with subCommands, and support for multiple commands.
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
public class FuzzySearch {
private static HashMap<String,String[]> searchers = new HashMap<String,String[]>();
public static void addSearcher(String id, String[] words){
searchers.put(id,words);
}
public static void removeSearcher(String id){
searchers.remove(id);
}
public static void addWords(String id, String... wordsToAdd){
String[] currentWords = searchers.get(id);
//create new larger array and copy over old data
String[] words = new String[currentWords.length+wordsToAdd.length];
for(int i=0;i<currentWords.length;i++){
words[i]=currentWords[i];
}
//add new words
for(int i=0;i<wordsToAdd.length;i++){
words[i+currentWords.length]=wordsToAdd[i];
}
searchers.put(id, currentWords);
}
public static String[] getWords(String id){
return searchers.get(id);
}
public static String getClosestWord(String id, String search){
String match = "";
int smallestDistance = Integer.MAX_VALUE;
for(String word:searchers.get(id)){
int distance = StringUtils.getLevenshteinDistance(word, search);
if(distance<smallestDistance){
smallestDistance=distance;
match=word;
}
}
return match;
}
public static String[] getClosestWords(String id, final String search){
//sort words based on distance
String[] words = searchers.get(id);
Arrays.sort(words,new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
int d1 = StringUtils.getLevenshteinDistance(search, o1);
int d2 = StringUtils.getLevenshteinDistance(search, o2);
return Integer.signum(d1 - d2);
}
});
return words;
}
public static boolean isArg(String id, String search){
return Arrays.asList(searchers.get(id)).contains(search);
}
public static String[] getClosestWords(String id, final String search, int amount){
String[] closestWords = getClosestWords(id,search);
String[] trimmed = new String[amount];
for(int i=0;i<closestWords.length;i++){
if(i<trimmed.length){
trimmed[i] = closestWords[i];
}
}
return trimmed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment