-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStage5.java
81 lines (75 loc) · 2.97 KB
/
Stage5.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import helper.Help;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* The program can successfully search for all matching lines.
* And the search is case- and space-insensitive.
* Problem handled: Need to check each line to find out whether it contains the query string.
* To optimize the program,
* used data structure called an Inverted Index.
* It maps each word to all positions/lines/documents in which the word occurs.
* As a result, when we receive a query,
* we can immediately find the answer without any comparisons.
*/
public class Stage5 {
public static String readFile(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
public static void print() {
System.out.println("==Menu==");
System.out.println("1. Find a person");
System.out.println("2. Print all people");
System.out.println("0. Exit");
}
public static void main(String[] args) throws Exception {
String fileName = args[1];
String text = readFile(fileName);
ArrayList<String> listOfPerson = new ArrayList<>();
Scanner scanner = new Scanner(text);
while (scanner.hasNext()) {
listOfPerson.add(scanner.nextLine());
}
Map<String,ArrayList<Integer>> invertedIndex = new HashMap<>();
for (int i = 0; i < listOfPerson.size(); i++) {
String[] personDetails = listOfPerson.get(i).split(" ");
for (String personDetail : personDetails) {
invertedIndex.putIfAbsent(personDetail.toLowerCase(), new ArrayList<>());
invertedIndex.get(personDetail.toLowerCase()).add(i);
}
}
scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
print();
int choice = Help.getChoice(scanner);
switch (choice) {
case 0 :
exit = Help.choice0();
break;
case 2 :
Help.choice2(listOfPerson);
break;
case 1 :
System.out.println("Enter a name or email to search all suitable people.");
String toSearch = scanner.nextLine();
if (invertedIndex.get(toSearch.toLowerCase()) != null) {
ArrayList<Integer> indices = invertedIndex.get(toSearch.toLowerCase());
for (int index : indices) {
System.out.println(listOfPerson.get(index));
}
} else {
System.out.println("No matching people found.");
}
break;
default :
System.out.println("Incorrect option! Try again.");
}
}
scanner.close();
}
}