structure/sparse_array/array2/array2.go
2019-04-12 04:48:54 +08:00

91 lines
1.6 KiB
Go

package array2
type Array2 struct {
sizes []int
ysize int
xsize int
data [][]interface{}
}
func New() *Array2 {
return NewWithCap(8, 8)
}
func NewWithCap(ysize, xsize int) *Array2 {
arr := &Array2{ysize: ysize, xsize: xsize}
arr.sizes = make([]int, arr.ysize, arr.ysize)
arr.data = make([][]interface{}, arr.ysize, arr.ysize)
return arr
}
func (arr *Array2) Values() []interface{} {
var result []interface{}
for _, y := range arr.data {
if y != nil {
for _, v := range y {
if v == nil {
result = append(result, struct{}{})
} else {
result = append(result, v)
}
}
} else {
for i := 0; i < arr.ysize; i++ {
result = append(result, nil)
}
}
}
return result
}
func (arr *Array2) Set(idx int, value interface{}) {
yindex := idx / arr.ysize
xindex := idx % arr.ysize
ydata := arr.data[yindex]
if ydata == nil {
ydata = make([]interface{}, arr.xsize, arr.xsize)
arr.data[yindex] = ydata
}
if ydata[xindex] == nil {
arr.sizes[yindex]++
}
ydata[xindex] = value
}
func (arr *Array2) Get(idx int) (interface{}, bool) {
yindex := idx / arr.ysize
xindex := idx % arr.ysize
ydata := arr.data[yindex]
if ydata == nil {
return nil, false
}
xdata := ydata[xindex]
return xdata, xdata != nil
}
func (arr *Array2) Del(idx int) (interface{}, bool) {
yindex := idx / arr.ysize
xindex := idx % arr.ysize
ydata := arr.data[yindex]
if ydata == nil {
return nil, false
}
xdata := ydata[xindex]
ydata[xindex] = nil
isnil := xdata != nil
if isnil {
arr.sizes[yindex]--
if arr.sizes[yindex] == 0 {
arr.data[yindex] = nil
}
}
return xdata, isnil
}