Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Printing out the least occurring elements in an array [closed]

Tags:

java

arrays

I am given an array of size 10 and I want to write a program that prints out the elements that occur the least and the number of times they occur.

For example for the array: 1 2 3 3 2 2 4 4 5 4 The program should print.. Elements: 1 5, and the number of occurrences should be 1

What I have so far prints out the most occurrences and only prints out one element.

public class Question3 {

  public static void main (String[] args) { 

     int[] testarray = {1,2,3,3,2,2,4,4,5,4};
     int count = 0;
     int bigCount = 10;

      for (int i=0; i < array.length; i++) {
        for (int j=0; j < array.length; j++) {
          if(array[j] == array[i]) {
             count++;
        }
    }
        if(count > bigCount) {
          bigCount = count;
          array[i] = random;
      }
    }
 System.out.println("num of elements and occurences: " + maxCount);
  }
}
like image 436
user2980566 Avatar asked Dec 05 '25 14:12

user2980566


1 Answers

You'll need a data structure to hold each unique element and it's count, Map<Integer,Integer> is probably your best bet. Iterate over your array like you are right now, and keep the counts as you go. Something like this:

public static void main(String[] args) {

    int[] array = {1,2,3,3,2,2,4,4,5,4};
    //create the map like this: <Element,Count>
    Map<Integer, Integer> counts = new HashMap<>();

    for (Integer i : array) {
        if (counts.get(i) == null) {
            counts.put(i, 1);
        } else {
            counts.put(i, counts.get(i) + 1);
        }
    }

    //find min value by sorting values and taking top element
    List<Integer> cs = new ArrayList<Integer>(counts.values());
    Collections.sort(cs);
    int minVal = cs.get(0);

    //find elements with minVal as their count
    List<Integer> minElements = new ArrayList<>();
    for (Entry<Integer, Integer> entry : counts.entrySet()) {
        if (entry.getValue() == minVal) {
            minElements.add(entry.getKey());
        }
    }
    //spit out each element and the count
    for (Integer i : minElements) {
        System.out.println("Element: " + i + " Number of occurences: "
                + minVal);
    }

}

Not terribly efficient but it gets it done.

like image 80
Durandal Avatar answered Dec 08 '25 02:12

Durandal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!