Monday, January 21, 2019

go - Append slice to slice of slices



I have data structure:



type PosList []int


type InvertedIndex struct {
Capacity int
Len int
IndexList []PosList
}


I have problem with Add method:




func (ii *InvertedIndex) Add(posList PosList, docId int) {
if ii.Len == ii.Capacity {
newIndexList := make([]PosList, ii.Len, (ii.Capacity+1)*2)
for i := 0; i < ii.Len; i++ {
newIndexList[i] = make([]int, len(ii.IndexList[i]))
copy(newIndexList[i], ii.IndexList[i])
}
ii.IndexList = newIndexList
}


ii.IndexList = ii.IndexList[0 : ii.Len+2]
ii.IndexList[docId] = posList
return
}


Or, i try something like this:



func (ii *InvertedIndex) Add(posList PosList, docId int) {


if ii.Len == ii.Capacity {
newIndexList := make([]PosList, ii.Len, (ii.Capacity+1)*2)
copy(newIndexList, ii.IndexList)
ii.IndexList = newIndexList
}

ii.IndexList = ii.IndexList[0 : ii.Len+2]
ii.IndexList[docId] = posList
return
}



Both of them don't work, may be someone can explain how can i append a slice to structure like this.


Answer



You question is confusing. I assume that you are trying to create a typical inverted index. In which case, you probably want to do something like this:



package main

import "fmt"


type DocId int

type Positions []int

type docIndex struct {
docId DocId
positions Positions
}

type InvertedIndex struct {

docIndexes []docIndex
}

func New() *InvertedIndex {
return &InvertedIndex{}
}

func (ii *InvertedIndex) Add(docId DocId, positions Positions) {
for i, di := range (*ii).docIndexes {
if di.docId == docId {

di.positions = append(di.positions, positions...)
(*ii).docIndexes[i] = di
return
}
}
di := docIndex{
docId: docId,
positions: positions,
}
(*ii).docIndexes = append((*ii).docIndexes, di)

}

func main() {
ii := New()
docId := DocId(11)
positions := Positions{42, 7}
ii.Add(docId, positions)
positions = Positions{21, 4}
ii.Add(docId, positions)
docId = DocId(22)

positions = Positions{84, 14}
ii.Add(docId, positions)
fmt.Printf("%+v\n", *ii)
}


Output:



{docIndexes:[{docId:11 positions:[42 7 21 4]} {docId:22 positions:[84 14]}]}



The statement:



di.positions = append(di.positions, positions...)


appends a slice to a slice.







References:



Appending to and copying slices



Arrays, slices (and strings): The mechanics of 'append'



inverted index


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...