package com.wustyq.spaceArr; import java.io.*; import java.util.Arrays; /** * ClassName: SparseArray <br/> * Description: <br/> * date: 2021/9/7 0:05<br/> * * @author yiqi<br /> * @since JDK 1.8 */ public class SparseArray { public static void main(String[] args) throws Exception { //创建一个原始的二维数组 11*11 //0:表示没有棋子,1:表示黑子,2:表示蓝子 int[][] chessArr1 = new int[11][11]; chessArr1[1][2] = 1; chessArr1[2][3] = 2; //输出原始的二维数组 System.out.println("原始二维数组"); for (int[] row : chessArr1) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } //将二维数组 转 稀疏数组的思路 //1、先遍历二维数组 得到非0数据的个数 int sum = 0; for (int[] row : chessArr1) { for (int data : row) { if (data != 0) { sum++; } } } System.out.println("sum=" + sum); //2、创建对应的稀疏数组 int[][] sparseArr = new int[sum + 1][3]; //给稀疏数组赋值 sparseArr[0][0] = 11; sparseArr[0][1] = 11; sparseArr[0][2] = sum; //遍历二维数组,将非0的值存放到 sparseArr int initRow = 1; for (int i = 0; i < chessArr1.length; i++) { for (int j = 0; j < chessArr1[i].length; j++) { if (chessArr1[i][j] != 0) { sparseArr[initRow][0] = i; sparseArr[initRow][1] = j; sparseArr[initRow][2] = chessArr1[i][j]; initRow++; } } } //输出稀疏数组的形式 System.out.println("得到的稀疏数组为~~~"); for (int[] row : sparseArr) { System.out.printf("%d\t%d\t%d\n", row[0], row[1], row[2]); } //将稀疏数组恢复成原始数组 int chessArr2_row = sparseArr[0][0]; int chessArr2_col = sparseArr[0][1]; int[][] chessArr2 = new int[chessArr2_row][chessArr2_col]; for (int i = 1; i < sparseArr.length; i++) { chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; } //输出原始数组的形式 System.out.println("原始数组的形式为~~~"); for (int[] row : chessArr2) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } //IO操作 //创建 输出 字符流 FileOutputStream fos = new FileOutputStream("src/data.txt"); for (int[] row : sparseArr) { for (int data : row) { fos.write((data + "\t").getBytes("utf8")); } fos.write("\r\n".getBytes("utf8")); } fos.flush(); fos.close(); //创建输入流 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/data.txt"))); int[][] sparseArr2 = new int[3][3]; //确定 读到了哪一行 int count = 0; while (true){ String line = br.readLine(); if (line == null){ break; } String[] split_ret = line.split("\t"); for (int i = 0; i < split_ret.length; i++) { sparseArr2[count][i] = Integer.parseInt(split_ret[i]); } count++; } br.close(); //输出 读取的数组 System.out.println("文件读取后数组的形式为~~~"); for (int[] row : sparseArr2) { for (int data : row) { System.out.printf("%d\t",data); } System.out.println(); } } }
java基础之 IO 流(InputStream/OutputStream)_我想月薪过万的博客-CSDN博客
java基础之 IO 流(输入/出字符流)_我想月薪过万的博客-CSDN博客