FoodPart1.java


Below is the syntax highlighted version of FoodPart1.java.


/******************************************************************* 
 Reference solution for Spring 2013 COS 126 Programming Exam 1
 Foodlympics Part One: Competitive Cuisine

 Author:       COS 126 Staff
 Netid:        cos126
 Precepts:     lots of them
 Dependencies: StdIn, StdOut
 Usage:        java FoodPart1 
 
 Description:  Reads in judge rankings for C countries by J judges.
               Prints out the rounded average score for each country,
               excluding the min and max.

**************************************************************************/

public class FoodPart1 {
    
    // excluding the min and max, compute the rounded average
    // of the entries of judgeRatings
    public static int score(int[] judgeRatings) {

        int J = judgeRatings.length;              
        int sum = 0;

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < J; i++) {
            min = Math.min(min, judgeRatings[i]);
            max = Math.max(max, judgeRatings[i]);
            sum += judgeRatings[i];
        }                                         

        // eliminate min and max
        sum = sum - min - max;
        
        // average
        double ave = sum / (double) (J - 2);
        
        // rounded average, excluding min and max
        int score = (int) Math.round(ave);
        return score;
    }

    // read the judges' ratings for several countries
    // from standard input and print their overall scores
    // to standard output
    public static void main(String[] args) {
        int C = StdIn.readInt(); // number of countries
        int J = StdIn.readInt(); // number of judges

        StdOut.println(C);       // first line of output

        // for each country, process their ratings
        for (int i = 0; i < C; i++) {

            // read the next line of input
            String name = StdIn.readString();
            int[] ratings = new int[J];
            for (int j = 0; j < J; j++)
                ratings[j] = StdIn.readInt();

            // compute the overall score
            int overall = score(ratings);

            // output for this country
            StdOut.println(name + " " + overall);
        }
    }
}