Home > Net >  What is the easiest or best way to find the peak in a square 2D array using brute force?
What is the easiest or best way to find the peak in a square 2D array using brute force?

Time:11-28

I want to find the peak in a square 2 dimensional array with x rows and x columns containing random values, and the peak should be the highest value in the array and alson higher than its 4 neighbours , North, South, West, East.

CodePudding user response:

Brute force suggests you're just going through the array looking at every possibility. If that's the case, you should just look at every value in the array. Also, the value is guaranteed to be higher than its neighbors if the value is the highest in the array. If you wanted to find the position in the array you could do something like:

int[][] array = {{2, 3, 4, 6},
                 {4, 3, 2, 9},
                 {3, 2, 1, 5}};

int maxX = 0, maxY = 0; // the location of maximum value to start
int maxFound = 0; // assuming positive values

for (int x = 0; x < array.length; x  ) {
    for (int y = 0; y < array[x].length; y  ) {
    
        // if current value in array at (x, y) is greater than maxFound,
        // update maxFound, maxX, and maxY:
        if (maxFound < array[x][y]) {
            maxFound = array[x][y];
            maxX = x;
            maxY = y;
        }
    }
}

System.out.println("The max was: "   maxFound   " at position: "   maxX   " "   maxY);

I'm not sure if this is what you wanted, but linearly searching through an unsorted array isn't necessarily brute force. Either way, you would have to look at every value in the 2D array, so if you're wondering about complexity, linear O(n) where n = array.length * array[0].length is as fast as this could be unless the 2D array is in some more sorted structure before we start working with it.

CodePudding user response:

Try this.

public static void main(String[] args) {
    int[][] matrix = {{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }};
    int peak = Stream.of(matrix)
        .flatMapToInt(row -> IntStream.of(row))
        .max().getAsInt();
    System.out.println(peak);
};

output:

8
  • Related