学习内容:
稀疏矩阵转换 课后作业:将二维矩阵转换成稀疏矩阵表示并存储到磁盘内,然后讲系数矩阵表示从磁盘中读取恢复为原矩阵。 Java IO流
学习产出:
public class SparseArray {
public static void main(String[] args) {
int chess[][] = new int[11][11];
chess[1][2] = 1;
chess[2][3] = 2;
System.out.println("-----------------------------");
System.out.println("初始稀疏矩阵");
System.out.println("-----------------------------");
for (int[] row : chess) {
for (int data : row) {
System.out.printf("%d ", data);
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chess[i][j] != 0) {
sum++;
}
}
}
System.out.println("-----------------------------");
System.out.println("初始稀疏矩阵中非零元素个数");
System.out.println(sum);
System.out.println("-----------------------------");
int sparseArray[][] = new int[sum + 1][3];
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chess[i][j] != 0) {
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chess[i][j];
}
}
}
System.out.println("得到的稀疏数组为:");
System.out.println("-----------------------------");
for (int i = 0; i < sparseArray.length; i++) {
System.out.printf("%d\t%d\t%d\t", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
System.out.println();
}
int chessRecon[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i=1;i<sparseArray.length;i++){
chessRecon[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
System.out.println("-----------------------------");
System.out.println("矩阵恢复之后");
System.out.println("-----------------------------");
for (int[] row : chessRecon) {
for (int data : row) {
System.out.printf("%d ", data);
}
System.out.println();
}
}
}
暂时只做了相互转换,IO流不熟悉明天做。
|