package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
type SparseArrayNode struct {
Row int
Col int
Val int
}
func main() {
// 稀疏数组可以看做是普通数组的压缩,但是这里说的普通数组是值无效数据量远大于有效数据量的数组
// 1.原数组中存在大量的无效数据,占据了大量的存储空间,真正有用的数据却少之又少
// 2.压缩存储可以节省存储空间以避免资源的不必要的浪费,在数据序列化到磁盘时,压缩存储可以提高IO效率
// 0 0 0 0 0
// 0 0 1 0 0 5 5 0
// 0 0 0 2 0 => 1 2 1
// 0 0 0 0 0 2 3 2
// 0 0 0 0 0
var chessMap [11][11]int
chessMap[1][2] = 1
chessMap[2][3] = 2
// 1.原始数组
fmt.Println("原始数组...")
for _, v := range chessMap {
for _, vv := range v {
fmt.Printf("%d ", vv)
}
fmt.Println()
}
// 2.压缩稀疏数组
sparseArray := make([]SparseArrayNode, 0)
// 初始化表头信息
sparseArray = append(sparseArray, SparseArrayNode{Row: 11, Col: 11, Val: 0})
for k, v := range chessMap {
for kk, vv := range v {
if vv != 0 {
sparseArray = append(sparseArray, SparseArrayNode{Row: k, Col: kk, Val: vv})
}
}
}
fmt.Println("压缩后数组...")
for _, v := range sparseArray {
fmt.Printf("%2d %2d %2d\n", v.Row, v.Col, v.Val)
}
// 保存到文件中 sparse_array.data
filePath := "./sparse_array.data"
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Println("open file err:", err.Error())
return
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, v := range sparseArray {
writer.WriteString(fmt.Sprintf("%d %d %d\n", v.Row, v.Col, v.Val))
}
writer.Flush()
// 3.从文件中恢复
recSparseArray := make([]SparseArrayNode, 0)
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
strArr := strings.Split(strings.Trim(str, "\n"), " ")
row, _ := strconv.Atoi(strArr[0])
col, _ := strconv.Atoi(strArr[1])
val, _ := strconv.Atoi(strArr[2])
recSparseArray = append(recSparseArray, SparseArrayNode{Row: row, Col: col, Val: val})
}
// 初始化全0数组
recChessMap := make([][]int, recSparseArray[0].Row)
for i := 0; i < recSparseArray[0].Row; i++ {
recChessMap[i] = make([]int, recSparseArray[0].Col)
}
for k, v := range recSparseArray {
if k == 0 {
continue
}
recChessMap[v.Row][v.Col] = v.Val
}
fmt.Println("恢复的数组....")
for _, v := range recChessMap {
for _, vv := range v {
fmt.Printf("%d\t", vv)
}
fmt.Println()
}
}
有疑问加站长微信联系(非本文作者)