import java.io.*;
public class TestDemo {
public static void main(String[] args) {
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
//将二维数组转化成稀疏数组
//1.遍历二维数组,找到有效的数据个数sum
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
//2.遍历二维数组,给稀疏数组赋值
int[][] sparseArr = new int[sum + 1][3];
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1[0].length;
sparseArr[0][2] = sum;
int count = 1;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
count++;
}
}
}
//3.遍历稀疏数组
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr[0].length; j++) {
System.out.print(sparseArr[i][j] + "\t");
}
System.out.println();
}
//4.将稀疏数组保存到map.txt中
saveArray("e:\\map.txt", sparseArr);
//5.从文件读取稀疏数组创建数组
int[][] chessArr2 = readArray("e:\\map.txt");
//6.遍历二维数组
for (int i = 0; i < chessArr2.length; i++) {
for (int j = 0; j < chessArr2[i].length - 1; j++) {
System.out.print(chessArr2[i][j] + "\t");
}
System.out.println();
}
}
public static void saveArray(String filePath, int[][] array) {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(filePath));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if (j == array[0].length - 1) {
bufferedWriter.write(array[i][j] + "");
} else {
bufferedWriter.write(array[i][j] + ",");
}
}
bufferedWriter.newLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static int[][] readArray(String filePath) {
BufferedReader bufferedReader = null;
int[][] destArray = new int[0][];
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
String[] split;
destArray = null;
int countLine = 0;
while ((line = bufferedReader.readLine()) != null) {
countLine++;
split = line.split(",");
if (countLine == 1) {
destArray = new int[Integer.parseInt(split[0])][Integer.parseInt(split[1])];
countLine++;
} else {
destArray[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = Integer.parseInt(split[2]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return destArray;
}
}
Java二维数组转稀疏数组(文件保存与读取)
最新推荐文章于 2024-07-17 20:43:45 发布