稀疏数组

原始数组 转化为 稀疏数组保存到文件 代码如下

// 二维数组压缩为稀疏数组
@Test
	public void test(){
		//创建原始数组
		int chessArr1[][] = new int[11][11];
		chessArr1[1][2] = 1;
		chessArr1[2][3] = 2;
		chessArr1[3][4] = 2;
		//显示遍历
		System.out.println("原始的二维数组。。");
		for(int[] row:chessArr1){
			for (int i : row) {
				System.out.printf("%d\t",i);
			}
			System.out.println();
		}
		
		//遍历数值个数
		System.out.println("转化为稀疏数组。。");
		int sum = 0 ;
		for (int i = 0; i < 11; i++) {
			for (int j = 0; j < 11; j++) {
				if(chessArr1[i][j] != 0 ){
					sum++;		
				}
			}
		}
		//创建稀疏数组
		int sparseArr[][] = new int[sum+1][3];
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter("read.txt");
			bw = new BufferedWriter(fw);
			bw.write(11+" ");
			bw.write(11+" ");
			bw.write(sum+" ");
			bw.newLine();
			
			int count = 0;
			for (int i = 0; i < 11; i++) {
				for (int j = 0; j < 11; j++) {
					if(chessArr1[i][j] != 0 ){
						bw.write(i+" ");
						bw.write(j+" ");
						bw.write(chessArr1[i][j]+" ");
						bw.newLine();
					}
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(bw != null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fw != null){
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	
	}

文件 稀疏数组转化为原始数组 代码如下

// 稀疏还原二维数组
@Test
	public void test1() throws IOException{
		FileReader fr=new FileReader("read.txt");
		BufferedReader br= new BufferedReader(fr);
		String str="";
		
		//保存每行数据到list集合
		List<String> list=new ArrayList<>();
		while((str = br.readLine()) != null){
			list.add(str);
		}
		str = (String)list.get(0);
		String[] split = str.split(" ");
		int chessArrL[][] =new int[Integer.parseInt(split[0])][Integer.parseInt(split[1])];	
		for (int i =1; i <Integer.parseInt(split[2])+1 ; i++) {
			String str1 =(String)list.get(i);
			String[] s = str1.split(" ");
			chessArrL[Integer.parseInt(s[0])][Integer.parseInt(s[1])]=Integer.parseInt(s[2]);
		}
		for(int[] row:chessArrL) {
			for(int data:row) {
				System.out.printf("%d\t",data);
			}
			System.out.println();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值