structure/sparse_array/array2/array2.go

91 lines
1.6 KiB
Go
Raw Normal View History

2019-04-11 20:48:54 +00:00
package array2
2019-04-11 13:34:50 +00:00
type Array2 struct {
sizes []int
ysize int
xsize int
data [][]interface{}
}
func New() *Array2 {
2019-04-11 20:48:54 +00:00
return NewWithCap(8, 8)
2019-04-11 13:34:50 +00:00
}
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
2019-04-11 20:48:54 +00:00
xindex := idx % arr.ysize
2019-04-11 13:34:50 +00:00
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
2019-04-11 20:48:54 +00:00
xindex := idx % arr.ysize
2019-04-11 13:34:50 +00:00
ydata := arr.data[yindex]
if ydata == nil {
return nil, false
}
2019-04-11 20:48:54 +00:00
xdata := ydata[xindex]
return xdata, xdata != nil
2019-04-11 13:34:50 +00:00
}
func (arr *Array2) Del(idx int) (interface{}, bool) {
yindex := idx / arr.ysize
2019-04-11 20:48:54 +00:00
xindex := idx % arr.ysize
2019-04-11 13:34:50 +00:00
ydata := arr.data[yindex]
if ydata == nil {
return nil, false
}
2019-04-11 20:48:54 +00:00
xdata := ydata[xindex]
2019-04-11 13:34:50 +00:00
ydata[xindex] = nil
2019-04-11 20:48:54 +00:00
isnil := xdata != nil
2019-04-11 13:34:50 +00:00
if isnil {
arr.sizes[yindex]--
if arr.sizes[yindex] == 0 {
arr.data[yindex] = nil
}
}
2019-04-11 20:48:54 +00:00
return xdata, isnil
2019-04-11 13:34:50 +00:00
}