Learn —————— Sparse array

Talk about what is a program?
There are endless explanations on the Internet, here is the answer from Baidu Baike:

  • A computer program is a set of computer can recognize and execute the instructions , to run on a computer, a certain tool for people to meet the information needs.

So how do you understand it? (Welcome to leave a message and exchange)

  • My understanding is: program = data structure + algorithm

Data structure: the way a computer stores and organizes data.

Data structure diagram:
Insert picture description here
linear structure:
1) As the most commonly used data structure, linear structure is characterized by a one-to-one linear relationship between data elements.
For example: one yuan in mathematics, one yuan quadratic equation in a y value corresponds to an x ​​value
2) Linear structure has two different storage structures, namely sequential storage structure and chain storage structure. The linear table stored in sequence is called the sequential table, and the storage elements in the sequential table are continuous.
3) The linear table stored in the chain is called the linked list. The storage elements in the linked list are not necessarily continuous. The data elements and relative data are stored in the element nodes. Address information of neighboring elements.
4) Common linear structures are: arrays, queues, linked lists and stacks

Non-linear structures include: two-dimensional arrays, multi-dimensional arrays, generalized tables, tree structures, graph structures

Algorithm: the method and logic to solve the problem.

In fact, you can feel better when you are working on a project-because you can complete an independent project without using a framework (the purpose of the framework is to simplify development and develop faster), so the core of the general project will be to rewrite the business logic (service layer).

It can be seen how important the data structure and algorithm are, so I recently started to brush the video learning data structure and algorithm on station B. After all, these two pieces are still very important.

1. What is a sparse array?

Sparse arrays are still a new wave of arrays after reviewing the past.
What is an array?

  • It is the collection elements of the same data type arranged in a certain order

Then you can take a look at the array below to see if it means this

		//字符数组
		char[] value = {
    
    'A', 'B'};
		//int数组
        int[] arr[] = {
    
    1, 2, 3, 4};

The sparse array is defined like this:

  • When most of the elements of an array are 0, or have the same value, you can use a sparse array to save the array.
    To put it bluntly, it means to record non-zero or the same value elements in the array.

The sparse array processing method is:
1. Record the total number of rows and columns in the array, and how many different values ​​are there.
2. Record the ranks and values ​​of elements with different values ​​in a small-scale array, thereby reducing the size of the program

Diagram (two-dimensional array): The
Insert picture description here
general process: the
first row: where 5, 5, and 9 respectively indicate that the array has 5 rows and 5 columns with 9 different values. The
second row: indicates that the first value is 22. The position of the array is The first row with index 0 and the second column element with index 2. The
third row: indicates that the second value is 13 The position of the array is the first row with index 0 and the
fourth column with index 4 Row: Indicates that the third value is 10 and the position of the array is the first row with index 1 and the second column with index 1

2. Why use sparse arrays?

After introducing sparse arrays, when should sparse arrays be used?
Usage scenario: Gobang (equivalent to a two-dimensional array)
Insert picture description here

The picture above is a 14*14 backgammon board. At this time, two players are playing a game and one player has played a pawn. Suddenly, they temporarily stopped playing. At this time, 14*14 only played two pawns, and the rest of the space is a bit wasted.
At this time, the sparse array came out. He said that I can help you transform. I will help you save the chess pieces played by the two players and their positions.

Represented by a sparse array (illustration):

Insert picture description here

3. How to manipulate sparse arrays?

In Gobang, 1 means black and 2 means blue (because white is not obvious on the board, it is replaced by blue). The
specific operation steps:

1. Convert the original array to a sparse array

  1. Use an array to create a chessboard with 14 rows and 14 columns
  2. Valid data is stored in a two-dimensional array
  3. Find the number of valid data sum. From the above diagram, we can know that the row of the sparse array is sum+1, and the column is fixed to 3

Second, the sparse array is stored to disk

  1. Write to disk using IO stream

Three, read sparse array from disk

  1. Use IO stream to read sparse array

Four, sparse array to original array

  1. Create the original array where the rows of the original array are the values ​​of the elements in the first row and the first column of the sparse array, and the columns are the values ​​of the elements in the first row and the second column of the sparse array

                         **********************代码实现**********************
    
01 The original array created:
       //创建原始数组14行14列
        int[][] chessArray = new int[14][14];
        //有效数据存放到二维数组中
        chessArray[1][3] = 1;
        chessArray[2][5] = 2;
        //求出有效数据个数
        int sum=0;
        for (int i = 0; i < chessArray.length; i++) {
    
    
            for (int j = 0; j < chessArray[i].length; j++) {
    
    
                if (chessArray[i][j] != 0) {
    
    
                    sum++;
                }
            }
        }
        //遍历查看一下
        for (int[] data:chessArray) {
    
    
            for (int ele:data) {
    
    
                System.out.printf("%d\t", ele);
            }
            System.out.println();
        }

Original array display

Insert picture description here

02Original array to sparse array code
 		System.out.println("稀疏数组~~~~~~~");
        //确定稀疏数组的行列数
        int[][] sparseArray = new int[sum + 1][3];
        //确定的数据存入稀疏数组(指的是行列数和有效值)
        sparseArray[0][0] = 14;
        sparseArray[0][1] = 14;
        sparseArray[0][2] = 2;
        //遍历原始数组将有效数据存入稀疏数组

        int count = 0;
        for (int i = 0; i < chessArray.length; i++) {
    
    
            for (int j = 0; j < chessArray[i].length; j++) {
    
    
                if (chessArray[i][j] != 0) {
    
    
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chessArray[i][j];
                }
            }
        }
		//遍历稀疏数组
        for (int[] data : sparseArray) {
    
    
            for (int ele : data) {
    
    
                System.out.printf("%d\t", ele);
            }
            System.out.println();
        }

Sparse array display

Insert picture description here

03 Write sparse array to disk
       //将稀疏数组写入磁盘
        String pathName = "D:/sparse/data.txt";
        File file = new File(pathName);
        if (!file.exists()) {
    
    
            //目录不存在创建文件夹
            file.getParentFile().mkdirs();
        }
        //创建文件
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        for (int i = 0; i < sparseArray.length; i++) {
    
    
            for (int j = 0; j < sparseArray[i].length; j++) {
    
    
                fos.write(sparseArray[i][j]);
            }
        }
        //释放资源
        fos.close();
        System.out.println("写入成功!");

Sparse array after writing to disk

Insert picture description here

04 Disk data is restored to sparse array
 /**
         * 磁盘数据恢复为稀疏数组
         * 清空原先稀疏数组的所有元素
         * 使从磁盘中读取到的有效数据重写存入sparseArray中 不用再次创建一个数组
         */
        //清空sparseArray数组
        for (int i = 0; i < sparseArray.length; i++) {
    
    
            for (int j = 0; j < sparseArray[i].length; j++) {
    
    
                sparseArray[i][j]=0;
            }
        }
        //清空后的数组
        for (int i = 0; i < sparseArray.length; i++) {
    
    
            for (int j = 0; j < sparseArray[i].length; j++) {
    
    
                System.out.printf("%d\t",sparseArray[i][j]);
            }
            System.out.println();
        }
        //读取磁盘数据重新存入到sparseArray中
        for (int i = 0; i < sparseArray.length; i++) {
    
    
            for (int j = 0; j < sparseArray[i].length; j++) {
    
    
                int read = fis.read();
                sparseArray[i][j]=read;
            }
        }
        System.out.println("恢复后的稀疏数组~~~~~");

        for (int[] data : sparseArray) {
    
    
            for (int ele : data) {
    
    
                System.out.printf("%d\t", ele);
            }
            System.out.println();
        }

Insert picture description here

05 Convert sparse array to original array
		 //稀疏数组转为原始数组
        int[][] chessArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];
        //将稀疏数组数据写入原始数组中
        /**
         * 1  3  1
         * 2  5  2
         */
        for (int i = 1; i < sparseArray.length; i++) {
    
    
            chessArray2[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][2];
        }
        System.out.println("原始数组~~~~~");
        for (int[] ints : chessArray2) {
    
    
            for (int ele : ints) {
    
    
                System.out.printf("%d\t", ele);
            }
            System.out.println();
        }

Finally, verify: if you add two more elements or more to the original original array, check the effect!

		//添加两个元素
		chessArray[5][6] = 1;
        chessArray[13][13] = 2;

Insert picture description here
to sum up:

  1. The original array is indeed modified, and the sparse array also changes!
    That's it! ! !

Guess you like

Origin blog.csdn.net/lirui1212/article/details/109723408