javaarraysmatrixmaxone-simulator

How to get Maximum value in multiple array?


I want to take the maximum value obtained from result.length, but I have trouble in the way to call it, can you help me?

double[][] result =  matrixMultiplexing(neighboursAdjSquare(matrixEgoNetwork), matrixDecrement(ones, matrixEgoNetwork));
double max = result[0][0];
    ArrayList<Double> val= new ArrayList<>();
    for (int i = 0; i < result.length; i++) {
        for (int j = i+1; j < result.length; j++) {
            Arrays.sort(result);
            if(result[i][j]== "I wanna called here" ){

                    val.add(result[i][j]);

            }
        }
    }

The error is cannot applied 'double',double[]' can you help me fix that?


Solution

  • public class FindMaxOf2dArray {
    public static void main(String[] argv) {
        double[][] arr2d =  new double[][]{
            {1.0, 2.0, 3.0, 4.0},
            {5.0, 6.0, 7.0, 8.0},
            {99.0, 0.0, 0.0, -1.0}
        };
        double maxOfarr2d = findMaxOf2dArray(arr2d);
    
        System.out.println("The maximum value contained in arr2d is " + maxOfarr2d);
    }
    
    static double findMaxOf2dArray(double[][] arr2d){
        double maxValue = Double.MIN_VALUE; 
    
        for(int i = 0; i < arr2d.length; i++){ //iterate through the number of arrays 
            for(int j = 0; j < arr2d[i].length; j++){//iterate through each value in the given array
                if(arr2d[i][j] > maxValue){
                    maxValue = arr2d[i][j];
                }
            }
        }
    
        return maxValue;
    }
    

    }

    This would be the most straight-forward way to find the maximum value within a 2d-array. Not necessarily the best way, but it should be easy to follow the logic. In the method findMaxOf2dArray(double[][]) we set the maximum value to the smallest possible value that can be stored in a double. Then we enter a for-loop that loops through each array that contains doubles. For every iteration of this loop we enter a second for-loop that iterates through each value stored in the current array. Each value is then compared against the value stored in maxValue. If the value stored in the array is greater than the value stored in maxValue, then we change the value of maxValue to the value stored in the array. Finally after checking each value in each array of the 2d-array, we return the value stored in maxValue.

    I believe the problem with your code is that you never iterate through the values stored in each array. You only iterate through the arrays themselves–twice. Each value stored in result[i] is itself an array which holds the double values that you want to compare. Additionally by starting j at i + 1 you skip i + 1 values to be iterated through. Lastly, a double cannot be compared to a String.