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

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]


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值