2

My question is if I input two maxvalue numbers in array, ex. 100, 10, 100. How can i get the output to print both index numbers?

The output expected would be 100 on index 1 and index 3 the index has 1 added as I want the index to start at one not zero

Javakiddie
  • 35
  • 5

2 Answers2

1

Add this to initialization.

HashSet<Integer> maxIndices = new HashSet<Integer>();

Make a second pass through the mileage array and add any max values to the HashSet.

The other option is to use a HashMap where the first integer is the mileage and the second value is the positive integer of how many have been found.

Because it makes only one pass, it may be faster even though you are counting every mileage, not just the one that ends up being the largest. Whether it is will be, of course, dependent upon the data, the compiler, and environmental conditions at the time of execution.

For your return value, you'll either need a custom POJO Java Bean or you can use Pair<> or Tuple<>. (See Using Pairs or 2-tuples in Java.)

Douglas Daseeco
  • 3,475
  • 21
  • 27
-1

Just simple Java using a series of for loops. The below method will return a 2D int array with each row consisting of two columns, the highest array value and its' respective array index number.

public int[][] getAllMaxValues(int[] allValues) {
    int maxVal = 0;
    int counter = 0;
    // Get the Max value in array...
    for (int i = 0; i < allValues.length; i++) {
        if (allValues[i] > maxVal) { 
            maxVal = allValues[i]; 
        }
    } 

    // How many of the same max values are there?
    for (int i = 0; i < allValues.length; i++) {
        if (allValues[i] == maxVal) {
            counter++;
        }
    }

    // Place all the max values and their respective
    // indexes into a 2D int array...
    int[][] result = new int[counter][2];
    counter = 0;
    for (int i = 0; i < allValues.length; i++) {
        if (allValues[i] == maxVal) {
            result[counter][0] = maxVal;
            result[counter][1] = i;
            counter++;
        }
    }

    // Return the 2D Array.
    return result;
}

How you might use this method:

int[] allMiles = {100, 10, 100, 60, 20, 100, 34, 66, 74};
int[][] a = getAllMaxValues(allMiles);

for (int i = 0; i < a.length; i++) {
    System.out.println("Array max value of " + a[i][0] + 
                       " is located at index: " + a[i][1]);
}

Console window would display:

Array max value of 100 is located at index: 0
Array max value of 100 is located at index: 2
Array max value of 100 is located at index: 5
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22