• + 0 comments

    For anyone having trouble in Java: I have yet to optimize this but I was able to pass all test cases except the last one (TestCase 3):

    public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            List<Float> arr = new ArrayList<>();
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()) {
                float f = sc.nextFloat();
                arr.add(f);
            }
            int size = arr.size()-1;
            arr.remove(0); // remove first element because it's just size of array
            float mean = 0;
            float median = 0;
            float mode = 0;
            
            // Sort array
            Collections.sort(arr);
            
            // Calculate mean
            for(int i = 0; i < arr.size(); i++) {
                mean += arr.get(i);
            }
            mean = (mean/arr.size());
            System.out.println(mean); // Print out mean
            
            // Calculate median 
            if(arr.size() % 2 == 0) {
                float num1 = arr.get((int)(arr.size()/2));
                float num2 = arr.get((int)(arr.size()/2)-1);
                median = ((num1+num2)/2);
            } else {
                median = arr.get(((int)arr.size()/2)+1);
            }
            System.out.println(median); // Print out median
            
            // Calculate mode
            Map<Float,Integer> modeMap = new TreeMap<>();
            
            for(float f: arr) {
                if(modeMap.containsKey(f)) {
                    int count = modeMap.get(f);
                    modeMap.replace(f,count++);
                } else {
                    modeMap.put(f,0);
                }
            }
            
            int count = 1; // counter to exit loop
            for(Map.Entry<Float,Integer> entry1 : modeMap.entrySet()) {
                while(count < arr.size()){
                    for(Map.Entry<Float,Integer> entry2 : modeMap.entrySet()) {
                        if(entry1.getValue() >= entry2.getValue() && entry1.getKey() < entry2.getKey()) {
                            mode = entry1.getKey();
                            break;
                        }
                        else if(entry1.getKey() == entry2.getKey()) {
                            mode = entry1.getKey();
                        }
                        count++;
                    }
                }
            }
        
            System.out.println(mode); // Print out mode
            
        }