Implementation of sparse array in Java language

Posted by will on Mon, 21 Feb 2022 12:03:29 +0100

Sparse array

About the author

  • Author introduction

🍓 Blog home page: Author URI

🍓 Introduction: high quality creator in JAVA field 🥇, A junior at school 🎓, During school, he participated in various provincial and national competitions and won a series of honors 🏆

🍓 Pay attention to me: pay attention to my learning materials and document downloads, update articles regularly every day, and encourage me to be a senior JAVA programmer 👨‍💻


In the Gobang program, it has the functions of saving, exiting and continuing the upper board.

We found that every time the program starts, its pieces can still be in the previous position. How does this happen? Today we'll explore the principle.

Analyze the problem:

Many values of the two-dimensional array are the default value of 0, so many meaningless data are recorded (here we call it invalid data) - > sparse array.

Basic introduction

When most elements in an array are 0 or an array with the same value, sparse array can be used to save the array.

The processing method of sparse array is:

  1. How many rows and columns are there in the record array? How many different values are there
  2. Record the rows, columns and values of elements with different values in a small-scale array, so as to reduce the size of the program

Application examples

  • Keep the two-dimensional array similar to the previous one (chessboard, map, etc.)
  • Save the sparse array and restore the original number of two-dimensional arrays

graphic

The idea of converting two-dimensional array to sparse array:

  1. Traverse the original two-dimensional array to get the number of valid data sum

  2. Based on sum, you can create a sparse array sparseArr int[sum + 1] [3]

  3. Store the valid data of the two-dimensional array into the sparse array

The idea of transforming sparse array into original two-dimensional array:

  1. First read the first row of the sparse array and create the original two-dimensional array according to the data of the first row, such as chessArr2 = int [11] [11]

  2. After reading a few rows of data from the sparse array, assign it to the original two-dimensional array

code implementation

package day1;


public class SparseArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//Create a new binary array 11 * 11
		int [][] chess = new int [11][11];
		chess[1][2] = 1;
		chess[2][3] = 2;
		System.out.println("Original array——————————————————");
		for(int[] row:chess){
			for(int data:row){
				System.out.printf("%d\t",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="+sum);
		
		
		System.out.println("Sparse array——————————————————");
		System.out.println("row\tcol\tvalue");
		//Create sparse array
		int [][] sparseArray = new int [sum+1][3];
		sparseArray[0][0] = 11;
		sparseArray[0][1] = 11;
		sparseArray[0][2] = sum;
		
		int count=0;//count is used to record the number of non-zero data
		// Traverse the two-dimensional array and store non-zero values in sparseArr
		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];
				}
			}
		}
		//Output sparse array
		for (int i = 0; i < sparseArray.length; i++) {
			System.out.println(sparseArray[i][0]+"\t"+sparseArray[i][1]+"\t"+sparseArray[i][2]);
		}
	
		//Restore sparse array to original array
		int [][]chess2 = new int [sparseArray[0][0]][sparseArray[0][1]];
		//Note that i starts from 1 instead of 0 during recovery
		//The number of cycles is also the length of the previous sparse array
		for (int i = 1; i < sparseArray.length; i++) {
			chess2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
		}
		System.out.println();
		System.out.println();
		System.out.println("Recovered 2D array——————————————————");
		for(int[] row:chess){
			for(int data:row){
				System.out.printf("%d\t",data);
			}
			System.out.println();
		}
	}
}

After class practice

  1. Based on the above, save the sparse array to disk, such as map data

  2. When restoring the original array, read the map Data recovery

file:

package com.cz.Sparsearray;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @ProjectName: Data_structure
 * @Package: com.cz.Sparsearray
 * @ClassName: SparseArrayWrite
 * @Author: Zhang Shengrui
 * @Date: 2022/2/21 17:34
 * @Version: 1.0
 */
public class SparseArrayWrite {
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //Create a new binary array 11 * 11
        int[][] chess = new int[11][11];
        chess[1][2] = 1;
        chess[2][3] = 2;
        System.out.println("Original array——————————————————");
        for (int[] row : chess) {
            for (int data : row) {
                System.out.printf("%d\t", 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=" + sum);


        //Create sparse array
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        int count = 0;//count is used to record the number of non-zero data
        // Traverse the two-dimensional array and store non-zero values in sparseArr
        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];
                }
            }
        }
        File file = new File("./data/map.data");
        if(!file.getParentFile().exists()){//Parent directory
            file.getParentFile().mkdirs();//Create parent directory
        }
        if(file.exists()){//File exists
            file.delete();
        }else{//file does not exist
            file.createNewFile();//create a file
        }
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fileWriter);
        System.out.println("On file......");
        for (int i = 0; i < sparseArray.length; i++) {
            String s = "" + sparseArray[i][0] + "\t" + sparseArray[i][1] + "\t" + sparseArray[i][2] + "\t\n";
            bw.write(s);
        }
        //Output sparse array
        System.out.println("Sparse array——————————————————");
        System.out.println("row\tcol\tvalue");
        for (int i = 0; i < sparseArray.length; i++) {
            System.out.println(sparseArray[i][0] + "\t" + sparseArray[i][1] + "\t" + sparseArray[i][2]);
        }
        bw.close();
    }
}

File reading:

package com.cz.Sparsearray;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: Data_structure
 * @Package: com.cz.Sparsearray
 * @ClassName: SparseArrayRead
 * @Author: Zhang Shengrui
 * @Date: 2022/2/21 17:51
 * @Version: 1.0
 */
public class SparseArrayRead {
    public static void main(String[] args) throws IOException {
        File file = new File("./data/map.data");
        if(file.getParentFile().exists()&&file.exists()){//Parent and child directories exist
            System.out.println("Start reading files......");
        }else {
            System.out.println("There are no files under this file");
        }
        FileReader fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(fileReader);
        List<String> list = new ArrayList<>();
        String s = "";
        while ((s = br.readLine()) != null){
            list.add(s);
        }
        //Create sparse array
        int sparseArrayRead[][] = new int [list.size()][3];
        String  s1 = list.get(0);
        String split[] = s1.split("\t");
        //Build a two-dimensional table of sparse array
        sparseArrayRead[0][0] = Integer.parseInt(split[0]);
        sparseArrayRead[0][1] = Integer.parseInt(split[1]);
        sparseArrayRead[0][2] = Integer.parseInt(split[2]);

        // Read the array in the file and output it to the array
        for (int i = 1; i < list.size(); i++) {
            String s2 = list.get(i);
            String split1[] = s2.split("\t");
            for (int j = 0; j < split1.length; j++) {
                sparseArrayRead[i][j] = Integer.parseInt(split1[j]);
            }
        }
        //Output sparse array
        for (int i = 0; i < sparseArrayRead.length; i++) {
            System.out.println(sparseArrayRead[i][0] + "\t" + sparseArrayRead[i][1] + "\t" + sparseArrayRead[i][2]);
        }


        //Restore sparse array to original array
        int[][] chess2 = new int[sparseArrayRead[0][0]][sparseArrayRead[0][1]];
        //Note that i starts from 1 instead of 0 during recovery
        //The number of cycles is also the length of the previous sparse array
        for (int i = 1; i < sparseArrayRead.length; i++) {
            chess2[sparseArrayRead[i][0]][sparseArrayRead[i][1]] = sparseArrayRead[i][2];
        }
        System.out.println();
        System.out.println("Recovered 2D array——————————————————");
        for (int[] row : chess2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}

Topics: Java Back-end