main.go
// Go语言·数据结构
package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
var content string = `
————————————————Go语言·数据结构————————————————————
一、稀疏数组
1.记录数组一共有几行几列,有多少个不同的值
2.把具有不同的值的元素行列及值记录在一个小规模的数组中,从而缩小程序的规模
0 0 0 1
0 3 0 0
0 0 5 0
1 0 0 0
row col val
4 4 0
0 3 1
1 1 3
2 2 5
3 0 1
`
type data struct {
row int
col int
val int
}
func main() {
readArr()
}
// 从原来数组---》生成稀疏数组--》保存文件
func storArr() {
var orginArr [11][11]int
rand.Seed(time.Now().UnixNano())
for i := 0; i < 5; i++ {
row := rand.Intn(11)
col := rand.Intn(11)
val := rand.Intn(11)
orginArr[row][col] = val
}
for _, val := range orginArr {
for _, v := range val {
fmt.Printf("%d\t", v)
}
fmt.Println()
}
fmt.Println()
var simpleSlice []data
simpleSlice = append(simpleSlice, data{row: len(orginArr), col: len(orginArr[0]), val: 0})
for i, val := range orginArr {
for j, v := range val {
if v == 0 {
continue
}
dta := data{
row: i,
col: j,
val: v,
}
simpleSlice = append(simpleSlice, dta)
}
}
for _, val := range simpleSlice {
fmt.Printf("%d\t%d\t%d \n", val.row, val.col, val.val)
}
// 1.新建一个文件,写入内容
var filepath = "D:/日常工作/go/src/day35/dta.data"
file, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("err=%v \n", err)
return
}
// 及时关闭句柄,否则会有内存泄漏
defer file.Close()
// *writer 使用带缓存的。
writer := bufio.NewWriter(file)
for _, val := range simpleSlice {
content := fmt.Sprintf("%d\t%d\t%d\n", val.row, val.col, val.val)
writer.WriteString(content)
}
// 将缓存中的数据,写入的文件
writer.Flush()
}
// 从文件中读取稀疏数组,恢复到原来数组结构
func readArr() {
var simpleSlice []data
var filepath = "D:/日常工作/go/src/day35/dta.data"
file, err := os.Open(filepath)
defer file.Close()
if err != nil {
fmt.Println("OpenFile ERR:", err)
return
}
// *reader 带缓冲
reader := bufio.NewReader(file)
// 循环读取
for {
// 一行一行的读取
str, err := reader.ReadString('\n')
// io.EOF表示文件的末尾
if err == io.EOF {
break
}
fmt.Print(str)
strArr := strings.Split(strings.Trim(str, "\n"), "\t")
row, _ := strconv.Atoi(strArr[0])
col, _ := strconv.Atoi(strArr[1])
val, _ := strconv.Atoi(strings.Trim(strArr[2], " "))
dta := data{
row: row,
col: col,
val: val,
}
simpleSlice = append(simpleSlice, dta)
}
orginArr := make([][]int, simpleSlice[0].row)
for i := 0; i < simpleSlice[0].row; i++ {
orginArr[i] = make([]int, simpleSlice[0].col)
}
for key, val := range simpleSlice {
if key == 0 {
continue
}
orginArr[val.row][val.col] = val.val
}
fmt.Println()
for _, val := range orginArr {
for _, v := range val {
fmt.Printf("%d\t", v)
}
fmt.Println()
}
}