1
我想在內存中表示超圖。嵌套矩陣旁邊的任務有沒有更好的數據結構?嵌套矩陣是一個矩陣,它可以具有「原生」類型(爲了簡單起見,假設爲
int
)和矩陣。在golang中實現嵌套矩陣的語言方式這是這樣一個矩陣的開始。代碼中是否有粗糙的邊緣,使其看起來更具慣用性?如何讓它看起來更習慣?
的代碼:
package main
import "fmt"
type Matricial interface {
Put(interface{}, ...int)
Get(...int) interface{}
}
type Matrix struct {
Matricial
values map[int]interface{}
}
func NewMatrix() *Matrix {
m := &Matrix{}
m.values = make(map[int]interface{})
return m
}
func (m *Matrix) Set(atom interface{}, pos ...int) {
firstdim := pos[0]
if val, ok := m.values[firstdim]; ok {
fmt.Println("map key exists", val)
switch converted := val.(type) {
case int:
m.values[firstdim] = converted
default:
fmt.Println("ERR: unknown type: %T", val)
}
} else {
if len(pos[1:]) > 0 {
newm := NewMatrix()
m.values[firstdim] = newm
newm.Set(atom, pos[1:]...)
} else {
m.values[firstdim] = atom
}
}
}
func (m *Matrix) Get(pos ...int) interface{} {
if len(pos) == 1 {
return m.values[pos[0]]
} else {
switch accessor := m.values[pos[0]].(type) {
case Matricial:
return accessor.Get(pos[1:]...)
default:
return nil
}
}
return nil
}
func main() {
m := NewMatrix()
m.Set(42, 2, 3, 4)
m.Set(43, 0)
fmt.Println(m.Get(2, 3))
fmt.Println(m.Get(2, 3, 4))
fmt.Println(m.Get(0))
}
數據結構必須允許與其它超邊連接超邊(即處理超邊,彷彿它們是節點)。
我認爲一個專門的Trie可能更適合你想要的東西。您不用文本前綴,而是使用索引序列前綴。 –
在這裏有一個很好的例子在C++:http://stackoverflow.com/questions/8348459/is-there-a-library-that-provides-a-directed-hypergraph-implementation-in-c。這可能有助於指引您朝正確的方向發展。否則,您使用地圖和切片對Go來說是慣用的。 – Intermernet