01
02
03
04
05
06
07
08
09
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
package algs35;
import stdlib.*;
import algs13.Bag;
/* ***********************************************************************
 *  Compilation:  javac MovieIndex.java
 *  Execution:    java MovieIndex movies.txt
 *  Dependencies: ST.java Bag.java In.java StdIn.java
 *
 *  % java MovieIndex movies-top-grossing.txt
 *  Stallone, Sylvester
 *    Rambo: First Blood Part II (1985)
 *    Rocky (1976)
 *    Rocky III (1982)
 *    Rocky IV (1985)
 *
 *  Hanks, Tom
 *    Apollo 13 (1995)
 *    Big (1988)
 *    Forrest Gump (1994)
 *    Green Mile, The (1999)
 *    League of Their Own, A (1992)
 *    Saving Private Ryan (1998)
 *    Sleepless in Seattle (1993)
 *    Toy Story (1995)
 *    Toy Story 2 (1999)
 *
 *  Apollo 13 (1995)
 *    Allen, Ivan
 *    Andrews, David
 *    Bacon, Kevin
 *    Barry, Thom
 *    Berkeley, Xander
 *    ...
 *
 *************************************************************************/


public class XMovieIndex {

  public static void main(String[] args) {

    // key = actor / movie, value = list of movies / actors
    ST<String, Bag<String>> st = new ST<>();

    // create inverted index of all files
    In in = new In(args[0]);
    while (in.hasNextLine()) {
      String line = in.readLine();
      String[] names = line.split("/");
      String movie = names[0];
      for (int i = 1; i < names.length; i++) {
        String actor = names[i];
        if (!st.contains(actor)) st.put(actor, new Bag<>());
        if (!st.contains(movie)) st.put(movie, new Bag<>());
        st.get(actor).add(movie);
        st.get(movie).add(actor);
      }
    }
    StdOut.println("Done indexing files");
    StdOut.println();

    StdOut.println("Type the name of a performer or movie");
    while (!StdIn.isEmpty()) {
      String name = StdIn.readLine();
      if (st.contains(name)) {
        for (String s : st.get(name))
          StdOut.println("  " + s);
      }
      StdOut.println();
    }
  }

}