Last active
August 29, 2015 14:07
-
-
Save prat0318/c420d915ea3e5130fcb6 to your computer and use it in GitHub Desktop.
Write a simple search engine which can locate a musical group from the attached dataset and return its url fragment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.HashMap; | |
import java.io.BufferedReader; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.IOException; | |
/* Basically create a cache by pre-processing | |
the data file. And then it is just a data | |
lookup. If i would have to implement a sub- | |
string search i would have built a trie instead. | |
As the cache load is just one time (during program | |
load) this makes querying very fast. | |
Usage: javac Searcher.java; java Searcher musical_group.tsv | |
*/ | |
public class Searcher { | |
private String filePath; | |
private HashMap<String, String> cache; | |
private void prompt() { | |
System.out.print("search> "); | |
} | |
public Searcher(String filePath) { | |
this.filePath = filePath; | |
this.cache = new HashMap<String, String>(); | |
} | |
public String search(String query) { | |
if(cache.containsKey(query)) | |
return cache.get(query); | |
else | |
return "Not found."; | |
} | |
public void preprocess() { | |
BufferedReader br = null; | |
String line = ""; | |
String tsvSplitBy = "\t"; | |
try { | |
br = new BufferedReader(new FileReader(this.filePath)); | |
br.readLine(); | |
while ((line = br.readLine()) != null) { | |
String[] items = line.split(tsvSplitBy); | |
cache.put(items[0], items[1]); | |
} | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (br != null) { | |
try { | |
br.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Searcher searcher = new Searcher(args[0]); | |
searcher.preprocess(); | |
searcher.prompt(); | |
Scanner scanner = new Scanner(System.in); | |
while(scanner.hasNext()) { | |
String results = searcher.search(scanner.nextLine()); | |
System.out.println(results); | |
searcher.prompt(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment