0

I need help on this problem:

Write the method mode that accepts an array of test grades(0 – 100) and return the mode, the grade that occurs most frequently. If there are multiple modes, return the smallest.

My code does not work: Please help, thanks!

public static int mode(int[] marks) {
    int count = 0;
    int count0 = 0;
    int mostFrequent = marks[0];
    for (int x = 0; x < marks.length; x++) {
        if (marks[x] == mostFrequent) {
            count++;
        }
    }
    if (count>count0) {
       count0  = count;
       mostFrequent = marks[count];
    }
    return mostFrequent;
}

E.g:

If marks = {1,2,4,6,1,1,1}, it works

if marks = {1,2,4,1,3,2,3,5,5}, it does not work

7
  • What does "does not work" mean? Are you getting an exception? Wrong results? Nov 30, 2020 at 8:47
  • Hi! Thanks for your reply. I am getting wrong results. It works sometimes and doesn’t other times.
    – cc123
    Nov 30, 2020 at 8:51
  • Can you please edit your question to add an example of an input that doesn't work, the result you expect and what you get instead? Nov 30, 2020 at 8:57
  • If you're going to do it with for loops, you'll need 2 nested loops. Take a step back, and re-think what you're doing. --- Alternatively, search the web for solutions, there are plenty out there.
    – Andreas
    Nov 30, 2020 at 9:10
  • Hi @FedericoklezCulloca, I edited it. Please take a look.
    – cc123
    Nov 30, 2020 at 9:12

2 Answers 2

1

You need to count the occurrence of all numbers. Try the following.

public static int mode(int[] marks) {
    Map<Integer, Integer> myMap = new HashMap<>();
    IntStream.of(marks).forEach(x -> myMap.merge(x, 1, Integer::sum)); // Take the occurences of each number
    Integer maxOccurence = Collections.max(myMap.values()); // Take the maximum
    return myMap.entrySet().stream().filter(entry -> entry.getValue() == maxOccurence).findFirst().get().getKey(); // Take the first(smallest) key which matches the maximum
}
0

This should do the trick:

 public static int mode(int[] marks) {
        return Arrays.stream(marks)
                .boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry<Integer, Long>::getValue).reversed().thenComparing(Map.Entry<Integer, Long>::getKey))
                .findFirst()
                .map(Map.Entry::getKey).orElse(0);
    }

Note: the last line sets 0 as a default value in case the array which is passed is empty.

 .map(Map.Entry::getKey).orElse(0);

If you want to throw an exception in such a case change it to:

 .map(Map.Entry::getKey).orElseThrow(RuntimeException::new);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.