二维数组转稀疏数组
import org.junit.Test;
import java.io.*;
/**
* 二维数组和稀疏数组的转化
*
* @author pjc
* @date 2021-02-01
**/
public class SparseArray {
@Test
public void test1() {
//创建原始的二维数组11*11,0-没有棋子,1-黑子,2-蓝子
int chess[][] = new int[11][11];
chess[1][2] = 1;
chess[2][3] = 2;
chess[2][4] = 1;
int sum = 0;
int col = 0;
System.out.println("原始二维数组:");
for(int[] arr : chess){
for (int data : arr){
if(data != 0){
sum ++;
}
System.out.printf("%s\t",data);
}
col ++;
System.out.println();
}
int sparseArray[][] = new int[sum+1][3];
sparseArray[0][0] = chess.length;
sparseArray[0][1] = col;
sparseArray[0][2] = sum;
//给稀疏数组赋值
int count = 0;
for (int i = 0; i < chess.length ;i++ ) {
for (int j = 0; j < col ;j++ ) {
if(chess[i][j] != 0){
count ++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chess[i][j];
}
}
}
System.out.println("转化后的稀疏数组:");
for(int[] arr : sparseArray){
for (int data : arr){
System.out.printf("%s\t",data);
}
System.out.println();
}
//将稀疏数组写入磁盘
//java8新特性,自动关流
File f = new File("sparseFile");
try (FileOutputStream out = new FileOutputStream(f); OutputStreamWriter outs = new OutputStreamWriter(out,"UTF-8")) {
System.out.println("将稀疏数组写入磁盘中....");
for (int i = 0; i < sparseArray.length ;i++ ) {
outs.write(sparseArray[i][0] + "," + sparseArray[i][1] + "," + sparseArray[i][2] + ",");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("数据写入磁盘成功");
System.out.println("稀疏数组开始读取:");
StringBuffer bf = null;
try (FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader in = new InputStreamReader(fileInputStream,"UTF-8")) {
System.out.println("将稀疏数组从磁盘中读出来....");
bf = new StringBuffer();
while (in.ready()){
bf.append((char)in.read());
}
} catch (IOException e) {
e.printStackTrace();
}
//每个数的数组
String[] split = bf.toString().split(",");
int sparseArray2[][] = new int[split.length/3][3];
sparseArray2[0][0] = Integer.parseInt(split[0]);
sparseArray2[0][1] = Integer.parseInt(split[1]);
sparseArray2[0][2] = Integer.parseInt(split[2]);
int n = 0;
for (int i = 3;i<split.length;i+=3) {
n++;
sparseArray2[n][0] = Integer.parseInt(split[i]);
sparseArray2[n][1] = Integer.parseInt(split[i+1]);
sparseArray2[n][2] = Integer.parseInt(split[i+2]);
}
System.out.println("读取后的稀疏数组::");
for(int[] arr : sparseArray2){
for (int data : arr){
System.out.printf("%s\t",data);
}
System.out.println();
}
//将稀疏数组还原成二维数组
int array2[][] = new int[sparseArray2[0][0]][sparseArray2[0][1]];
for (int i = 1; i < sparseArray2.length ;i++ ) {
array2[sparseArray2[i][0]][sparseArray2[i][1]] = sparseArray2[i][2];
}
System.out.println("将稀疏数组还原成二维数组:");
for(int[] arr : array2){
for (int data : arr){
System.out.printf("%s\t",data);
}
System.out.println();
}
}
}