Java 相邻数组的最小值
我需要帮助解决这个问题,我需要一个数组3x5,然后当用户选择一个位置时,输出将显示相邻数字的最小值。像这样:Java 相邻数组的最小值,java,arrays,Java,Arrays,我需要帮助解决这个问题,我需要一个数组3x5,然后当用户选择一个位置时,输出将显示相邻数字的最小值。像这样: 3 5 6 7 8 6 7 8 2 3 0 9 2 1 1 并且用户选择位置1,1对角线也算 输出:周围的最小值为0 这就是我拥有的代码,问题是我在问是否有比到处乱发if和else更好的方法 private static int checkAdjacentField(int p1, int p2, int[][] ae) { int min = Integer.MAX_VALU
3 5 6 7 8
6 7 8 2 3
0 9 2 1 1
并且用户选择位置1,1对角线也算
输出:周围的最小值为0
这就是我拥有的代码,问题是我在问是否有比到处乱发if和else更好的方法
private static int checkAdjacentField(int p1, int p2, int[][] ae) {
int min = Integer.MAX_VALUE;
if (p1 == 0) {
if (p2 == 0) {
if (ae[p1][p2+1] < min) {
min = ae[p1][p2+1];
} else if (ae[p1+1][p2+1] < min) {
min = ae[p1+1][p2+1];
} else if (ae[p1+1][p2] < min) {
min = ae[p1+1][p2];
}
} else if (p2 == 1) {
if (ae[p1][p2+1] < min){
min = ae[p1][p2+1];
} else if (ae[p1+1][p2+1] < min) {
min = ae[p1+1][p2+1];
} else if (ae[p1+1][p2] < min) {
min = ae[p1+1][p2];
} else if (ae[p1+1][p2-1] < min) {
min = ae[p1+1][p2-1];
} else if (ae[p1][p2-1] < min) {
min = ae[p1][p2-1];
}
}
}
return min;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random r = new Random();
int [][] ar = new int[3][5];
for (int i = 0; i < ar.length; i++) {
System.out.println();
for (int j = 0; j < 5; j++) {
int rand = r.nextInt(9) + 1;
ar[i][j]=rand;
System.out.printf("%3d",ar[i][j]);
}
}
System.out.println();
System.out.println("Select a position [][]: ");
int pos1 = Integer.parseInt(br.readLine());
int pos2 = Integer.parseInt(br.readLine());
System.out.println("The min value around is " + checkAdjacentField(pos1,pos2,ar));
}
}
private static int checkAdjacentField(int p1、int p2、int[]ae){
int min=整数最大值;
如果(p1==0){
如果(p2==0){
如果(ae[p1][p2+1]
在代码中,0,0和0,1起作用,是的,我可以花时间做if-else的垃圾邮件方法,但我想知道是否有更好的方法,以便改进。感谢您的帮助,欢迎您提供任何想法或答案。您可以使用类似这样的for循环来解析所有相邻单元格,将它们放入列表中,然后轻松计算该列表的最小值 这样,可以减少If分支的使用 adjRow==0&&adjCol==0===>中间单元格
int matrix[][]={{3, 5, 6, 7, 8},
{6, 7, 8, 2, 3} ,
{ 0,9,2,1,1}};
List adjacents = new ArrayList<>(8);
int row= 0 ; int col=1 ;
for (int adjRow = -1; adjRow <= 1; ++adjRow) {
for (int adjCol = -1; adjCol <= 1; ++adjCol) {
if ( (adjRow != 0 || adjCol != 0)
// Avoid IndexOutOfBoundsException
&& ( row + adjRow >= 0 && row + adjRow < 3 )
&& ( col + adjCol >= 0 && col + adjCol < 5 )
){
adjacents.add(matrix[row + adjRow][col + adjCol]);
}
}
}
System.out.println(Collections.min(adjacents));
在任何时候,我们都有8个相邻号码的可能位置。N、 西北、西、西南、南、东南、东、东北。因此,我们可以将它们全部添加到ArrayList中进行迭代并检查最小值,如果我们确信这样做不会使我们越界的话 这看起来很冗长,但是对于任何大小的2d数组,它都可以处理任何情况,无论是否为edge,并且可以与您提供的代码一起使用:
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class Test {
char[] array;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random r = new Random();
int [][] ar = new int[3][5];
for (int i = 0; i < ar.length; i++) {
System.out.println();
for (int j = 0; j < 5; j++) {
int rand = r.nextInt(9) + 1;
ar[i][j]=rand;
System.out.printf("%3d",ar[i][j]);
}
}
System.out.println();
System.out.println("Select a position [][]: ");
int pos1 = Integer.parseInt(br.readLine());
int pos2 = Integer.parseInt(br.readLine());
System.out.println("The min value around is " + checkAdjacentField(pos1,pos2,ar));
}
private static int checkAdjacentField(int y, int x, int[][] ae) {
int height = ae.length;
int width = ae[0].length;
int min = Integer.MAX_VALUE;
ArrayList<Integer> adj = new ArrayList<Integer>();
// CHECK NORTH, only out of bounds if we're at the NORTH (y == 0)
if (y != 0) { adj.add(ae[y-1][x]); }
// CHECK NORTHWEST, only out of bounds if we're at the NORTHWEST (y == 0 & x == 0)
if (y != 0 && x != 0) { adj.add(ae[y-1][x-1]); }
// CHECK WEST, only out of bounds if we're at the WEST (x == 0)
if (x != 0) { adj.add(ae[y][x-1]); }
// CHECK SOUTHWEST, only out of bounds if we're at the SOUTHWEST (y == (height-1) & x == 0)
if (y != (height-1) && x != 0) { adj.add(ae[y+1][x-1]); }
// CHECK SOUTH, only out of bounds if we're at the SOUTH (y == (height-1))
if (y != (height-1)) { adj.add(ae[y+1][x]); }
// CHECK SOUTHEAST, only out of bounds if we're at the SOUTHEAST (y == (height-1) & x == (width-1))
if (y != (height-1) && x != (width-1)) { adj.add(ae[y+1][x+1]); }
// CHECK EAST, only out of bounds if we're at the EAST (x == (width-1))
if (x != (width-1)) { adj.add(ae[y][x+1]); }
// CHECK NORTHEAST, only out of bounds if we're at the NORTHEAST (y == 0 & x == (width-1))
if (y != 0 && x != (width-1)) { adj.add(ae[y-1][x+1]); }
// Now, we check our min using our list that contains 3-8 entries
for (Integer num : adj) {
if (num < min) { min = num; }
}
return min;
}
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.Random;
公开课考试{
字符[]数组;
公共静态void main(字符串[]args)引发NumberFormatException,IOException{
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
随机r=新随机();
int[]ar=新int[3][5];
for(int i=0;i
这个怎么样
private static int checkAdjacentField(int p1, int p2, int[][] ae) {
int[] tmp = new int[8];
int left = (p2-1) % ae[0].length;
int right = (p2+1) % ae[0].length;
int up = (p1-1) % ae.length;
int down = (p1+1) % ae.length;
tmp[0] = ae[up][left];
tmp[1] = ae[up][p2];
tmp[2] = ae[up][right];
tmp[3] = ae[p1][left];
tmp[4] = ae[p1][right];
tmp[5] = ae[down][left];
tmp[6] = ae[down][p2];
tmp[7] = ae[down][right];
List<Integer> tmpList = Arrays.stream(tmp).boxed().collect(Collectors.toList());
return tmpList.stream().mapToInt(i -> i).min().orElse(0);
}
我认为最好的方法是使用以下算法:
- 所有相邻位置的列表(无论它们是否在阵列中)
- 筛选出不在数组中的
- 将其余位置映射到它们在数组中的值
- 查找最小的一个(当我们处理整数时,您可以对它们进行排序并取第一个)
private static int checkAdjacentField(int col, int row, int[][] ae) {
int nbRows = ae.length;
int nbCols = ae[0].length;
// Stream all the 8 positions around your position
Stream<Point> positions = Stream.of(
new Point(col-1, row-1), new Point(col-1, row), new Point(col-1, row+1),
new Point(col, row-1), new Point(col, row+1),
new Point(col+1, row-1), new Point(col+1, row), new Point(col+1, row+1));
return positions
.filter(p -> p.x>=0 && p.y>=0 && p.x<nbCols && p.y<nbRows) // keep those inbound
.mapToInt(p -> ae[p.y][p.x]) // replace positions by their values in the array
.sorted() // sort the values
.findFirst().orElse(-1); // take the first one (smallest)
}
私有静态int checkAdjacentField(int col,int row,
private static int checkAdjacentField(int col, int row, int[][] ae) {
int nbRows = ae.length;
int nbCols = ae[0].length;
// Stream all the 8 positions around your position
Stream<Point> positions = Stream.of(
new Point(col-1, row-1), new Point(col-1, row), new Point(col-1, row+1),
new Point(col, row-1), new Point(col, row+1),
new Point(col+1, row-1), new Point(col+1, row), new Point(col+1, row+1));
return positions
.filter(p -> p.x>=0 && p.y>=0 && p.x<nbCols && p.y<nbRows) // keep those inbound
.mapToInt(p -> ae[p.y][p.x]) // replace positions by their values in the array
.sorted() // sort the values
.findFirst().orElse(-1); // take the first one (smallest)
}
private static int checkAdjacentField(int col, int row, int[][] ae) {
int nbRows = ae.length;
int nbCols = ae[0].length;
// Stream all the 8 positions around your position
Stream<Point> positions = IntStream.rangeClosed(-1, 1).boxed() // -1, 0, 1
.map(c -> IntStream.rangeClosed(-1, 1).boxed() // -1, 0, 1
.map(r -> new Point(col+c, row+r)))
.flatMap(p -> p) // to a list
.filter(p -> !(p.x == col && p.y==row)); // remove center point
// then same as first example
return positions
.filter(p -> p.x>=0 && p.y>=0 && p.x<nbCols && p.y<nbRows)
.mapToInt(p -> ae[p.y][p.x])
.sorted()
.findFirst().orElse(-1);
}
private static int checkAdjacentField(int p1, int p2, int[][] ae) {
int minColIdx = p2 == 0 ? p2 : p2 - 1;
int minRowIdx = p1 == 0 ? p1 : p1 - 1;
int maxRowIdx = p1 == ae.length - 1 ? p1 : p1 + 1;
int result = Integer.MAX_VALUE;
for (int i = minRowIdx; i <= maxRowIdx; i++) {
int[] row = ae[i];
int maxColIdx = p2 == row.length - 1 ? p2 : p2 + 1;
for (int k = minColIdx; k <= maxColIdx; k++) {
if (!(p1 == i && p2 == k) && ae[i][k] < result) {
result = ae[i][k];
}
}
}
return result;
}
private static int checkAdjacentField(int p1, int p2, int[][] ae) {
int min = Integer.MAX_VALUE;
for (int i = p1 - 1; i <= p1 + 1; i++) {
for (int j = p2 - 1; j <= p2 + 1; j++) {
if ((i < 0 || j < 0) || (i > 2 || j > 4) || (i == p1 && j == p2)) {
continue;
}
if (ae[i][j] < min) {
min = ae[i][j];
}
}
}
return min;
}