structure/sparse_array/arrayn/arrayn.go

127 lines
2.4 KiB
Go
Raw Normal View History

2019-04-12 19:35:18 +00:00
package arrayn
type SizeN struct {
Sizes []int
}
type ProductN struct {
Values []int
}
type DimensionSize struct {
Sizes []int
}
type Node struct {
size int
data interface{}
}
type ArrayN struct {
dims []int
product []int
dim int
data *Node // []*Node
}
func New() *ArrayN {
return NewWithCap(8, 8, 8)
}
func NewWithCap(dims ...int) *ArrayN {
arr := &ArrayN{dim: len(dims), dims: dims}
arr.product = make([]int, len(dims)-1, len(dims)-1)
for i := 0; i < len(dims)-1; i++ {
pvalue := 1
for n := i + 1; n < len(dims); n++ {
pvalue *= dims[n]
}
arr.product[i] = pvalue
}
// arr.data = make([]*Node, arr.dims[0], arr.dims[0])
return arr
}
func (arr *ArrayN) Values() []interface{} {
return nil
}
func (arr *ArrayN) set(curDim int, curidx int, data **Node, parent *Node) (*Node, int) {
sidx := arr.dim - curDim
if *data == nil {
if parent != nil {
parent.size++
}
if curDim > 1 {
*data = &Node{data: make([]*Node, arr.dims[sidx], arr.dims[sidx])}
} else {
*data = &Node{data: make([]interface{}, arr.dims[sidx], arr.dims[sidx])}
return *data, curidx
}
}
if curDim == 1 {
return *data, curidx
}
nidx := curidx % arr.product[sidx]
dimindex := curidx / arr.product[sidx]
cur := *data
return arr.set(curDim-1, nidx, &cur.data.([]*Node)[dimindex], cur)
}
func (arr *ArrayN) get(curDim int, curidx int, data **Node) (*Node, int) {
sidx := arr.dim - curDim
if *data == nil {
return nil, 0
}
if curDim == 1 {
return *data, curidx
}
nidx := curidx % arr.product[sidx]
dimindex := curidx / arr.product[sidx]
cur := *data
return arr.get(curDim-1, nidx, &cur.data.([]*Node)[dimindex])
}
func (arr *ArrayN) Set(idx int, value interface{}) {
n, nidx := arr.set(arr.dim, idx, &arr.data, nil)
n.data.([]interface{})[nidx] = value
}
func (arr *ArrayN) Get(idx int) (interface{}, bool) {
n, nidx := arr.get(arr.dim, idx, &arr.data)
if n != nil {
v := n.data.([]interface{})[nidx]
return v, v != nil
}
return nil, false
}
func (arr *ArrayN) del(curDim int, curidx int, data **Node) (*Node, int) {
sidx := arr.dim - curDim
if *data == nil {
return nil, 0
}
if curDim == 1 {
return *data, curidx
}
nidx := curidx % arr.product[sidx]
dimindex := curidx / arr.product[sidx]
cur := *data
return arr.del(curDim-1, nidx, &cur.data.([]*Node)[dimindex])
}
func (arr *ArrayN) Del(idx int) (interface{}, bool) {
return nil, true
}