summaryrefslogtreecommitdiff
path: root/debugging/InvertedIndex.java
blob: 65284f71a9f340c7bc6ecc451a6fb01a7c4421e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;

public class InvertedIndex {
    public static void main(String[] args) {
        List<String> docs = new ArrayList<>();
        docs.add("Raiders of the Lost Ark");
        docs.add("The Temple of Doom");
        docs.add("The Last Crusade");
        
        Map<String, Set<String>> result = createIndex(docs);
        System.out.println(docs);
        System.out.println();
        System.out.println(result);
    }

    // TODO: Write and document your createIndex method here

    public static Map<String, Set<String>> createIndex(List<String> docs) {
        Map<String, Set<String>> index = new TreeMap<>();
        Set<String> uniqueWords = getUniqueWords(docs);

        for (String uniqueWord : uniqueWords) {
            index.put(uniqueWord.toLowerCase(), new HashSet<String>());
        }

        for (String word : index.keySet()) {
            for (int i = 0; i < docs.size(); i++) {
                Scanner wordScanner = new Scanner(docs.get(i));
                while (wordScanner.hasNext()) {
                    if (wordScanner.next().equalsIgnoreCase(word)) {
                        index.get(word).add(docs.get(i));
                    }
                }
            }
        }
        return index;
    }

    public static Set<String> getUniqueWords(List<String> docs) {
        Set<String> uniqueWords = new HashSet<>();
        for (String title : docs) {
            Scanner titleScanner = new Scanner(title);
            while (titleScanner.hasNext()) {
                uniqueWords.add(titleScanner.next());
            }
            titleScanner.close();
        }
        return uniqueWords;
    }

    
}