java一道关于二维数组的操作的题目

    xiaoxiao2021-03-25  148

    import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class test { /* * 有两个二维数组a[5][5]和数组b a数组如下: * [23, 12, 32, 41, 15] * [14, 21, 73, 14, 55] * [51, 12, 63, 34, 65] * [11, 21, 13, 14, 5] * [21, 12, 43, 24, 54] * 现将a数组中的每个数组取出其周边元素按照升序排列后,取周边元素个数除以2的那个值作为b数组的指定元素, * 例如a[0][0]的周边元素是{12,14,21},排序后是{12,14,21},中间值是3/2=1,即b[0][0]=14; * 又如:a[2][1]的周边元素是{14,21,73,51,63,11,21,13},排序后是{11,13,14,21,21,51,63,73} * 中间值是8/2=4,即b[2][1]=21.代码如下: * */ public static void main(String[] args) { int[][] a = { { 23, 12, 32, 41, 15 }, { 14, 21, 73, 14, 55 }, { 51, 12, 63, 34, 65 }, { 11, 21, 13, 14, 5 }, { 21, 12, 43, 24, 54 } }; int[][] b = new int[5][5]; System.out.println("原数组a:"); for (int i = 0; i < 5; i++) { int[] temp = a[i]; System.out.println(Arrays.toString(temp)); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { //用来存放a数组的中每一个元素的周围元素,以便以后排序并且取出指定的值付给b数组 //主要判断的条件是:i-1>=0,i+1<5,j-1>=0;j+1>5.只有满足这些条件的组合才不会有数组角标错误。 ArrayList<Integer> al = new ArrayList<Integer>(); if (i - 1 >= 0) {//当该元素的上一行存在 if (j - 1 >= 0)//当该列存在时 al.add(a[i - 1][j - 1]); al.add(a[i - 1][j]); if (j + 1 < 5)//当该列存在时 al.add(a[i - 1][j + 1]); } if (j - 1 >= 0) al.add(a[i][j - 1]); if (j + 1 < 5) al.add(a[i][j + 1]); if (i + 1 < 5) { if (j - 1 >= 0) al.add(a[i + 1][j - 1]); al.add(a[i + 1][j]); if (j + 1 < 5) al.add(a[i + 1][j + 1]); } Collections.sort(al);//升序排列 int size = al.size() / 2; b[i][j] = al.get(size); } } System.out.println("新数组b:"); for (int i = 0; i < 5; i++) { int[] temp = b[i]; System.out.println(Arrays.toString(temp)); } } }

    运行结果如下: 原数组a: [23, 12, 32, 41, 15] [14, 21, 73, 14, 55] [51, 12, 63, 34, 65] [11, 21, 13, 14, 5] [21, 12, 43, 24, 54] 新数组b: [14, 23, 21, 32, 41] [21, 32, 32, 55, 34] [14, 21, 21, 55, 14] [21, 21, 24, 43, 34] [12, 21, 14, 14, 14]

    转载请注明原文地址: https://ju.6miu.com/read-3365.html

    最新回复(0)