package senior_08_02; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class Devon { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); //Input and Output code from http://ace.delos.com/ioiupload?a=GPjC9fno73Y&javaio=1 // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader("DATACOMPRESSION.in")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( "DATACOMPRESSION.out"))); for (int i = 0; i < 5; i++) // 5 lines of input { hashTable = new String[SIZE]; redundancy = new int[SIZE]; String input = f.readLine(); // get input StringTokenizer st = new StringTokenizer(input); while (st.hasMoreTokens()) // search for redundancies { String s = st.nextToken(); // remove punctuation from tokens s = s.substring(0, punctuation(s)); // insert into hash table if (!s.equals("")) insert(s); } st = new StringTokenizer(input); int count = 1; String output = ""; while (st.hasMoreTokens()) // replace redundancies { String s = st.nextToken(); // separate punctuation from token String punct = ""; int point = punctuation(s); if (point < s.length()) { punct = s.substring(point, s.length()); s = s.substring(0, point); } if ( !s.equals("") ) { // find in hash table int index = search(s); // if redundant, set a number if (redundancy[index] == -1) { redundancy[index] = count; count++; s = Integer.toString(redundancy[index]); } else if (redundancy[index] != 0) s = Integer.toString(redundancy[index]); } // copy to output string if (!output.equals("")) output = output + " "; output = output + s + punct; } out.println( output ); } // end input System.out.println(System.currentTimeMillis() - start); out.close(); System.exit(0); } private static int punctuation(String s) { int p; for (p = s.length(); p > 0 && !Character.isLetter( s.charAt(p - 1) ); p--) ; return p; } private static void insert(String s) { int index = Math.abs( s.hashCode() ) % SIZE; while ( !(hashTable[index] == null || hashTable[index].equals(s)) ) { index = (index + 1) % SIZE; } // update redundancy table if (hashTable[index] != null) redundancy[index] = -1; else hashTable[index] = s; // insert string } private static int search(String s) { int index = Math.abs( s.hashCode() ) % SIZE; while ( !hashTable[index].equals(s) ) { index = (index + 1) % SIZE; } return index; } private static final int SIZE = 10000; private static String[] hashTable; private static int[] redundancy; }