golang 普通数组、稀疏数组互相转换,稀疏数组落盘
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
//稀疏数组的基本使用
func main() {
var arr [12][12]int
arr[1][1] = 1
arr[2][2] = 2
for _,item := range arr {
for _,val := range item {
fmt.Printf("%d ",val)
}
fmt.Println("")
}
//获取稀疏数组,将其写入磁盘
sparseArr := encodeSparseArray(arr)
//落盘
saveFile(sparseArr)
//2还原
sparseArr := readFile("sparseArray/sparse.data")
new := make([][]int,sparseArr[0][0])
for i:=0;i<sparseArr[0][0];i++{
new[i] = make([]int,sparseArr[0][1])
}
for k,item := range sparseArr {
if k == 0 {
continue
}
new[item[0]][item[1]] = item[2]
}
for _,item := range new {
for _,val := range item {
fmt.Printf("%d ",val)
}
fmt.Println("")
}
fmt.Println("success")
}
//将普通二维数组转换为稀疏数组
func encodeSparseArray(arr [12][12]int) [][3]int{
sli := make([][3]int,0)
var children [3]int
children[0] = len(arr)
children[1] = len(arr[0])
children[2] = 0
sli = append(sli, children)
for i,item := range arr {
for j,val := range item {
if val != 0 {
children[0] = i
children[1] = j
children[2] = val
sli = append(sli, children)
}
}
}
return sli
}
//保存在本地
func saveFile(sparseArr [][3]int){
//1、定义文件路劲
var filePath = "sparseArray/sparse.data"
//2、打开文件句柄
file,err := os.OpenFile(filePath,os.O_WRONLY|os.O_CREATE|os.O_TRUNC,0766)
if err != nil {
fmt.Printf("打开文件出错 err:%v\n",err)
return
}
//3、延时关闭资源
defer file.Close()
//4、创建缓冲区
buf := bufio.NewWriter(file)
//5、循环写入字符串
var data = ""
for _,item := range sparseArr {
data = fmt.Sprintf("%v|%v|%v\n",item[0],item[1],item[2])
_,err = buf.WriteString(data)
if err != nil {
fmt.Printf("写入缓冲区失败 err:%v\n",err)
return
}
}
//6、保存缓冲区
err = buf.Flush()
if err != nil {
fmt.Printf("保存缓冲区失败 err:%v\n",err)
}
}
//从文件读取数据,将其转化为稀疏数组
func readFile(filePath string)[][3]int{
file,err := os.OpenFile(filePath,os.O_RDONLY,0766)
if err != nil{
fmt.Printf("文件打开失败 err:%v\n")
}
defer file.Close()
buf := bufio.NewReader(file)
sparseArr := make([][3]int,0)
var children [3]int
for {
str ,err := buf.ReadString('\n')
if err != nil{
if err == io.EOF{
break
}else {
fmt.Printf("读取文件失败 err:%v\n",err)
}
}
str = strings.Trim(str,"\n")
//将字符串转为数组
sli := strings.Split(str," ")
for k,val := range sli {
val,err := strconv.Atoi(val)
if err != nil {
fmt.Printf("类型转换失败 err:%v\n",err)
}
children[k] = val
}
sparseArr = append(sparseArr, children)
}
return sparseArr
}
//将稀疏数组转换为二维数组
func decodeSparseArray(){
}