Java programming: Store the contents of the Gobang board to disk in a sparse matrix, and re-read the contents from it-sparse array and algorithm

1. Actual demand

  • There is a 存盘退出sum 续上盘function in the written Gobang program .
    Insert picture description here
  • Analysis of the problem:
    Because many values ​​of the two-dimensional array are default values 0, a lot of meaningless data is recorded.->Sparse array.

2. Sparse array

2.1 Basic introduction

When most of the elements in an array are or are 同一个值arrays, you can use a sparse array to save the array.

2.2 The processing method of sparse array is:

  1. The record array has several rows and columns, and how many different values ​​are there
  2. Record the ranks and values ​​of elements with different values ​​in a small array, thereby reducing the size of the program

2.3 Examples

The converted sparse array, the first row records the number of rows, the number of columns, and the amount of data that is not 0.
Each subsequent row records the non-zero value and its value.
Insert picture description here

3. Application examples

  1. Use sparse arrays to retain two-dimensional arrays similar to the previous ones (checkerboards, maps, etc.)
  2. Save the sparse array and restore the original two-dimensional array number
  3. Overall thinking analysis

Insert picture description here

3.1 Diagram

Insert picture description here

3.2 The idea of ​​converting a two-dimensional array to a sparse array

  1. Traverse the original two-dimensional array to get the number of valid data sum
  2. According to sum can create sparse array sparseArr int[sum + 1] [3]
  3. Store the valid data of the two-dimensional array into the sparse array

3.3 The idea of ​​converting sparse array to original two-dimensional array

  1. First read the first row of the sparse array, and create the original two-dimensional array based on the data in the first row, such as chessArr2 = int above [11][11]
  2. Then read the data in the last few rows of the sparse array and assign it to the original two-dimensional array.

4. Code Implementation

package sparseArray;

import java.io.*;
import java.util.Arrays;

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;
        // 输出原始的二维数组
        System.out.println("原始的二维数组为:");
        for (int[] rows : chessArr1) {
    
    
            for (int data : rows) {
    
    
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        // 二维数组转换为稀疏数组
        // 1. 先遍历二维数组,得到非0数据的个数
        int sum = 0;
        for (int i = 0; i < chessArr1.length; i++) {
    
    
            for (int j = 0; j < chessArr1[0].length; j++) {
    
    
                if (chessArr1[i][j] != 0) sum++;
            }
        }
        // System.out.printf("非零元素的个数为:%d",sum);
        // 2. 创建对应稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        // 3. 给稀疏数组赋值:第一行存储原始数据行列数以及非零元素个数,后面每行存每一个非零元素
        // 3.1 给第一行赋值
        sparseArr[0][0] = chessArr1.length;
        sparseArr[0][1] = chessArr1[0].length;
        sparseArr[0][2] = sum;
        // 3.2 遍历二维数组,将二维数组的非零元素存放到洗漱数组中
        int count = 0;  // count用于记录是第几个非零数据
        for (int i = 0; i < chessArr1.length; i++) {
    
    
            for (int j = 0; j < chessArr1[0].length; j++) {
    
    
                if (chessArr1[i][j] != 0) {
    
    
                    ++count;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }
        // 输出得到的稀疏数组
        System.out.println("得到的稀疏数组为:");
        String textStr = "";
        for (int[] rows : sparseArr) {
    
    
            for (int data : rows) {
    
    
                System.out.printf("%d\t", data);
                textStr = textStr + data + " ";
            }
            textStr += "\n";
            System.out.println();
        }

        // 4 将稀疏数组恢复成原始的二维数组
        // 4.1 读取第一行,根据第一行数据创建原始二维数组
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        // 4.2 读取稀疏数组后几行数据,赋值给原数组
        for (int i = 1; i < sparseArr.length; i++) {
    
    
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        // 输出恢复后的二维数组
        System.out.println("恢复后的二维数组为:");
        for (int[] rows : chessArr2) {
    
    
            for (int data : rows) {
    
    
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        System.out.println("要存入文件的内容为:");
        System.out.println(textStr);
        // 5. 将系数矩阵写到map.data
        saveFile(textStr, "map.data");
        String fileContent = readFile("map.data");
        System.out.println("通过文件读取出来的内容为:");
        System.out.println(fileContent);
    }

    /**
     * 读取文件
     * @param filePath 文件路径
     * @return 文件内容
     * @throws IOException
     */
    public static String readFile(String filePath) throws IOException {
    
    
        File file = new File(filePath);
        // 如果文件不存在则创建文件
        if (!file.exists()) {
    
    
            file.createNewFile();
        }
        InputStream inputStream = new FileInputStream(file);
        // 这里定义了数组的长度是1024个字节,如果文件超出这字节,就会溢出,结果就是读不到1024字节以后的东西
        byte[] bs = new byte[1024];
        // 这里len获得的是文件中内容的长度
        int len = inputStream.read(bs);
        inputStream.close();
        return new String(bs);
    }

    /**
     * 写文件
     * @param content 内容
     * @param filePath 路径
     */
    public static void saveFile(String content, String filePath) {
    
    
        File file = new File(filePath);
        OutputStream outputStream = null;
        if (!file.exists()) {
    
    
            try {
    
    
                // 如果文件找不到,就new一个
                file.createNewFile();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        try {
    
    
            // 定义输出流,写入文件的流
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        }
        // 定义将要写入文件的数据
        String string = content;
        // 把string转换成byte型的,并存放在数组中
        byte[] bs = string.getBytes();
        try {
    
    
            // 写入bs中的数据到file中
            outputStream.write(bs);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        try {
    
    
            outputStream.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }


}

The running result is:
Insert picture description here

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/108599468