+ 1
how to find max or min number in two dimensional array ?.
i think question is pretty self explainatory !!
6 odpowiedzi
+ 3
Bhushan Gaikwad there are various approach, objective is to find the precise output.
https://code.sololearn.com/chkVW58cQcRp/?ref=app
https://code.sololearn.com/c76vBXgdue86/?ref=app
+ 2
http://code.sololearn.com/c1seF47iVi0S
public class Program
{
public static int min(int[][] arr) {
if ((arr.length == 0)||(arr[0].length == 0)) {
throw new IllegalArgumentException("Empty array");
}
int min = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] < min) {
min = arr[i][j];
}
}
}
return min;
}
public static int max(int[][] arr) {
if ((arr.length == 0)||(arr[0].length == 0)) {
throw new IllegalArgumentException("Empty array");
}
int max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
return max;
}
public static void main(String[] args) {
int[][] arr = new int[][]{
{ 1, 4, 0, 6, -8, 8, 78 },
{ 3, 0, 0, 12, -7, 9, 0 },
{ 0, 64, 0, 0, -9, 4, 0 },
{ 2, 1, 0, -1, 0, -4, 0 },
{ 0, 0, 11, 8, 1, -2, 2 }
};
System.out.println(min(arr));
System.out.println(max(arr));
}
}
+ 1
Like with a classic array, only you use a nested loop instead of a simple one.
+ 1
int[][] ints = getInts(); /* some instantiation method */
int min = 2147483647; /* practically infinite for int types. */
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints[i].length; j++) {
if (ints[i][j] < min) min = ints[i][j];
}
}
0
can u give som rough code to understand it more !!
0
You could use Collections too
http://code.sololearn.com/cSHVVygDbuYI/#java
try below:
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[][] arr = {
{15, 12, 6},
{19, 7, 14, 11},
{2, 18, 5}
};
Integer max;
Integer min;
Integer num;
min = Collections.min(Arrays.asList(arr[0]));
max = Collections.max(Arrays.asList(arr[0]));
for (int i = 1; i < arr.length; i++) {
num = Collections.min(Arrays.asList(arr[i]));
if(num<min)min=num;
num = Collections.max(Arrays.asList(arr[i]));
if(num>max)max=num;
}
System.out.println("Max=" + max +" min=" + min);
}
}