Home > other >  How to print index of all maximum numbers without losing the index count?
How to print index of all maximum numbers without losing the index count?

Time:09-17

Let's say I have created an array

int[] maxNums = {62, 24, 54, 92, 12, 45, 75, 43, 46, 98, 23, 98};

I know how to print the maximum and its index. Here I have two repeated numbers 98, how do I print the index of the repeated maximum. 98 is both at the index 9 and 11.

        int[] maxNums = {62, 24, 54, 92, 12, 45, 75, 43, 46, 98, 23, 98};
        int maxmark = 0, index = 0;
        for(int i = 0; i < marks.length; i  ){
            if(marks[i] > maxmark){
                maxmark = marks[i];
                index = i;
            }
        }
        System.out.println("Maximum mark = "   maxmark   " Index = "   index);

CodePudding user response:

There are multiple ways to do so, if you know exactly there are always 2 instances you could just introduce a second index (index2). But generally, we want to be able to do this for an arbitrary number of occurrences of the max.

public class MyClass {
    public static void main(String args[]) {
        int[] maxNums = {62, 24, 54, 92, 12, 45, 75, 43, 46, 98, 23, 98};
        int[] idx = new int[10]; // last 10 
        int[] marks = maxNums; // Assuming this, different name in for loop
        int maxmark = 0, index = 0;
        for(int i = 0; i < marks.length; i  ){
            if(marks[i] > maxmark){
                maxmark = marks[i];
                index = 0;
                idx[index] = i;
            }else if (marks[i] == maxmark){
                index = index   1;
                idx[index] = i;
            }
        }
        
        for(int i = 0; i < index 1; i  ){
            System.out.println("Maximum mark = "   maxmark   " Index = "   idx[i]);
        }
    }
}

An even better approach would be Lists, which aren't statically allocated. This will break if there are more than 10 indexes of the max at a given time. Note, here index is just the location of the idx array.

CodePudding user response:

Instead of capturing a single index you need to capture (potentially) multiple indexes. Since you don't know how many there may be you can use a Collection. A List seems like a reasonable choice - specifically an ArrayList. You will need to adjust your output to accommodate multiple index values as well. It should look something like...

int[] maxNums = {62, 24, 54, 92, 12, 45, 75, 43, 46, 98, 23, 98};

int maxmark = 0;
List<Integer> indexes = new ArrayList<>();

for(int index = 0; index < marks.length; index  ) {
  if (marks[index] == maxmark) {
    indexes.add(index);
  } else if (marks[index] > maxmark) {
    maxmark = marks[index];
    indexes.clear();
    indexes.add(index);
  }
}
StringJoiner join = new StringJoiner(",");
indexes.stream().forEach(index -> join.add(index));

System.out.println("Maximum mark = "   maxmark   " Index(es) = "   join.toString());
  • Related