001package algs24;
002import stdlib.*;
003import algs12.Transaction;
004import algs13.Stack;
005/* ***********************************************************************
006 *  Compilation:  javac TopM.java
007 *  Execution:    java TopM M < input.txt
008 *  Dependencies: MinPQ.java Transaction.java StdIn.java StdOut.java
009 *  Data files:   http://algs4.cs.princeton.edu/24pq/tinyBatch.txt
010 *
011 *  Given an integer M from the command line and an input stream where
012 *  each line contains a String and a long value, this MinPQ client
013 *  prints the M lines whose numbers are the highest.
014 *
015 *  % java TopM 5 < tinyBatch.txt
016 *  Thompson    2/27/2000  4747.08
017 *  vonNeumann  2/12/1994  4732.35
018 *  vonNeumann  1/11/1999  4409.74
019 *  Hoare       8/18/1992  4381.21
020 *  vonNeumann  3/26/2002  4121.85
021 *
022 *************************************************************************/
023
024public class TopM {
025
026        // Print the top M lines in the input stream.
027        public static void main(String[] args) {
028                args = new String[] { "5" };
029                StdIn.fromFile ("data/tinyBatch.txt");
030
031                int M = Integer.parseInt(args[0]);
032                MinPQ<Transaction> pq = new MinPQ<>(M+1);
033
034                while (StdIn.hasNextLine()) {
035                        // Create an entry from the next line and put on the PQ.
036                        String line = StdIn.readLine();
037                        Transaction transaction = new Transaction(line);
038                        pq.insert(transaction);
039
040                        // remove minimum if M+1 entries on the PQ
041                        if (pq.size() > M)
042                                pq.delMin();
043                }   // top M entries are on the PQ
044
045                // print entries on PQ in reverse order
046                Stack<Transaction> stack = new Stack<>();
047                for (Transaction transaction : pq)
048                        stack.push(transaction);
049                for (Transaction transaction : stack)
050                        StdOut.println(transaction);
051        }
052}
053