import java.io.*;
//二维数组与稀疏数组
public class SparseArray {
public static void main(String[] args) throws IOException {
// 创建一个原始的二维数组11 * 11
// 0:表示没有棋子,1:表示黑子, 2:表示白子。
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][3] = 1;
chessArr1[2][4] = 2;
chessArr1[3][5] = 1;
// 输出原始的二维数组
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 i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
// 2.创建对应的稀疏数组
int sparseAee1[][] = new int[sum+1][3];
// 给稀疏数组赋值
sparseAee1[0][0] = 11;
sparseAee1[0][1] = 11;
sparseAee1[0][2] = sum;
// 遍历二维数组,将非0的值存放到sparseAee1中
int count = 0; // count 用于记录是第几个非0数据
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseAee1[count][0] = i;
sparseAee1[count][1] = j;
sparseAee1[count][2] = chessArr1[i][j];
}
}
}
// 遍历稀疏数组
System.out.println("这是稀疏数组:");
for ( int[] row : sparseAee1) {
for ( int data : row ){
System.out.printf("%d\t", data);
}
System.out.println();
}
File file = new File("map.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(fos,"UTF-8");
for (int i = 0; i < sparseAee1.length; i++) {
if ( i == sparseAee1.length - 1 ){
writer.append((sparseAee1[i][0]+","+sparseAee1[i][1]+","+sparseAee1[i][2]));
} else {
writer.append((sparseAee1[i][0]+","+sparseAee1[i][1]+","+sparseAee1[i][2]+","));
}
}
writer.close();
fos.close();
//Desktop.getDesktop().open(file);
FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis,"UTF-8");
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char)reader.read());
}
reader.close();
fis.close();
String[] str = sb.toString().split(",");
int sparseAee2[][] = new int[str.length / 3][3];
int n = 0;
for(String s : str){
sparseAee2[(n - (n % 3))/ 3][n % 3] = Integer.parseInt(s);
n++;
}
// 稀疏数组 转 二维数组
int chessArr2[][] = new int[sparseAee2[0][0]][sparseAee2[0][1]];
for (int i = 1; i < sparseAee2.length; i++) {
chessArr2[sparseAee2[i][0]][sparseAee2[i][1]] = sparseAee2[i][2];
}
System.out.println("这是二维数组2:");
for ( int[] row : chessArr2) {
for ( int data : row ){
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}
二维数组与稀疏矩阵相互转换
最新推荐文章于 2024-07-08 00:01:13 发布