此文章仅作为自己学习过程中的记录和总结,同时会有意地去用英文来做笔记,一些术语的英译不太准确,内容如有错漏也请多指教,谢谢!
一、概述
需要强调的是,稀松数组适用于二维数组中大部分数据具有相同的值的情况,此时稀松数组可以显著地提高算法效率。反之,若不在上述情况下使用稀松数组,则可能得到效率更低下的结果。
稀松数组的结构大体如下:
Index | Row | Column | Value |
---|---|---|---|
0 | 原数组行数 | 原数组列数 | 特殊数据的个数 |
1 | 特殊数据1所在行数 | 特殊数据1所在列数 | 特殊数据1的值 |
2 | … | … | … |
此例子为通过稀松数组记录棋盘上的每个格子的当前子色。(未下子:0; 黑子:1;白子:2)。此例子还包含IO相关知识。
步骤:
- 创建棋盘数组chessArr,并且对其进行初始化。
- 根据chessArr创建稀松数组sparseArr并打印。
- 将sparseArr存储到文件map.data中。
- 从map.data读取数据并根据之创建新的稀松数组。
- 利用新创建的稀松数组,对其进行转化,得到新的棋盘数组并打印。
二、代码实现
- Attributes and main
/*
SparseArray
Zzay
2021/01/14
*/
package com.zzay.sparsearray;
import java.io.*;
/**
* CONTENTS:
* (1) Initialize the chess array.
* (2) Create a sparse array according to the chess array.
* (3) Save the sparse array into the dest file "map.data".
* (4) Read the sparse array from the source file "map.data".
* (5) Convert the read sparse array into a new chess array.
* * @author Zzay
* @version 2021/01/14
*/
public class SparseArray {
public final static int ROW_SIZE = 11;
public final static int COLUMN_SIZE = 11;
public final static int NONE = 0;
public final static int BLACK = 1;
public final static int WHITE = 2;
public final static String fileName = "map.data";
public final static File destFile = new File(fileName);
public final static File srcFile = new File(fileName);
// The array representing the chessboard.
private static int[][] chessArr = new int[ROW_SIZE][COLUMN_SIZE];
// The sparse array to be formed.
private static int[][] sparseArr;
public static void main(String[] args) {
initialize();
createSparseArr();
saveSparseArr();
convertSparseArr(readSparseArr());
}
}
- Methods
/**
* The initialization of the chessArr.
*/
private static void initialize