001package algs35;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac Concordance.java
005 *  Execution:    java Concordance < input.txt
006 *  Dependencies: ST.java SET.java In.java StdIn.java Out.java
007 *
008 *  % java Concordance tale.txt
009 *  cities
010 *  tongues of the two *cities* that were blended in
011 *
012 *  majesty
013 *  their turnkeys and the *majesty* of the law fired
014 *  me treason against the *majesty* of the people in
015 *  of his most gracious *majesty* king george the third
016 *
017 *  princeton
018 *
019 *************************************************************************/
020
021public class XConcordance {
022
023        public static void main(String[] args) {
024                args = new String[] { "data/tale.txt" };
025                StdIn.fromString ("cities majesty");
026
027                int CONTEXT = 5;
028
029                In in = new In(args[0]);
030                String[] words = in.readAll().split("\\s+");
031                ST<String, SET<Integer>> st = new ST<>();
032
033                // build up concordance
034                for (int i = 0; i < words.length; i++) {
035                        String s = words[i];
036                        if (!st.contains(s)) {
037                                st.put(s, new SET<>());
038                        }
039                        SET<Integer> set = st.get(s);
040                        set.add(i);
041                }
042                StdOut.println("Finished building concordance");
043
044                // process queries
045                while (!StdIn.isEmpty()) {
046                        String query = StdIn.readString();
047                        SET<Integer> set = st.get(query);
048                        if (set == null) set = new SET<>();
049                        for (int k : set) {
050                                for (int i = Math.max(0, k - CONTEXT + 1); i < k; i++)
051                                        StdOut.print(words[i] + " ");
052                                StdOut.print("*" + words[k] + "* ");
053                                for (int i = k + 1; i < Math.min(k + CONTEXT, words.length); i++)
054                                        StdOut.print(words[i] + " ");
055                                StdOut.println();
056                        }
057                        StdOut.println();
058                }
059
060        }
061}