稀疏数组
- 稀疏数组
稀疏数组
package testimport ("encoding/json""fmt""io/ioutil""log""reflect""testing"
)type ValNode struct {Row int `json:"row"`Col int `json:"col"`Val int `json:"val"`
}func TestSparseArray(t *testing.T) {// 1 创建一个原始数组var chessMap [11][11]intchessMap[1][2] = 1chessMap[2][3] = 2// 2 输出看看原始数组for _, v := range chessMap {for _, v2 := range v {fmt.Printf("%d\t", v2)}fmt.Println()}// 3 转成稀疏数组var sparseArray []ValNodesparseArray = append(sparseArray, ValNode{len(chessMap), len(chessMap[0]), 0})for i, v := range chessMap {for j, v2 := range v {if v2 != 0 {// 创建一个值节点valNode := ValNode{Row: i,Col: j,Val: v2,}sparseArray = append(sparseArray, valNode)}}}// 输出稀疏数组for i, valNode := range sparseArray {fmt.Printf("%d: %d\t%d\t%d\n", i, valNode.Row, valNode.Col, valNode.Val)}// 将这个稀疏数组存盘// Serialize slice of ValNodemarshal, err := json.Marshal(sparseArray)if err != nil {log.Fatal("json.Marshal", err)}log.Println("Serialized slice of ValNode:", string(marshal))// to-dberr = ioutil.WriteFile("./output.txt", marshal, 0644)if err != nil {log.Fatal("写入文件时发生错误:", err)}log.Println("数据成功写入文件。")// read-dbdata, err := ioutil.ReadFile("./output.txt")if err != nil {log.Fatal("读取文件时发生错误:", err)}log.Println("数据成功写入文件。")// Deserialize slice of ValNodevar unmarshal []ValNodeerr = json.Unmarshal(data, &unmarshal)if err != nil {log.Fatal("json.Unmarshal", err)}log.Println("Deserialized slice of ValNode:", unmarshal)log.Println("Type of Deserialized slice of ValNode:", reflect.TypeOf(unmarshal))// 创建一个原始数组// 创建一个二维切片,包含 11 行chessMap2 := make([][]int, unmarshal[0].Row)// 初始化每一行元素为包含 11 个元素的切片for i := range chessMap2 {chessMap2[i] = make([]int, unmarshal[0].Col)}for i, valNode := range unmarshal {if i != 0 {chessMap2[valNode.Row][valNode.Col] = valNode.Val}}// 看看chessMap2 是不是恢复// 输出稀疏数组for _, v := range chessMap2 {for _, v2 := range v {fmt.Printf("%d\t", v2)}fmt.Println()}
}