package main
import (
"fmt"
"strings"
)
type InvertedIndexContainer[T Comparable[T]] struct {
Map map[string]*List[T]
}
func NewInvertedIndexContainer[T Comparable[T]]() *InvertedIndexContainer[T] {
return &InvertedIndexContainer[T]{
make(map[string]*List[T]),
}
}
func (i *InvertedIndexContainer[T]) Insert(doc string, id T) {
keys := strings.Split(doc, " ")
for _, key := range keys {
if i.Map[key] == nil {
i.Map[key] = NewList[T]()
}
i.Map[key].Insert(id)
}
}
func (i *InvertedIndexContainer[T]) GetKeysByID(id T) (res []string) {
for key, list := range i.Map {
if list.Search(id) {
res = append(res, key)
}
}
return
}
func (i *InvertedIndexContainer[T]) GetIndexesByKey(key string) (list *List[T], ok bool) {
list, ok = i.Map[key]
return
}
func (i *InvertedIndexContainer[T]) DeleteByID(id T) {
for key, list := range i.Map {
list.Delete(id)
if i.Map[key].Number == 0 {
delete(i.Map, key)
}
}
}
func (i *InvertedIndexContainer[T]) DeleteByKey(key string) {
delete(i.Map, key)
}
func (i *InvertedIndexContainer[T]) DeleteByKeyAndID(key string, id T) {
if list, ok := i.Map[key]; ok {
list.Delete(id)
}
}
func main() {
doc1 := "hello world 你好 文章1 ok smile"
doc2 := "good study sleep world mine smile"
iic := NewInvertedIndexContainer[MyInt]()
iic.Insert(doc1, MyInt(1))
iic.Insert(doc2, MyInt(2))
list, ok := iic.GetIndexesByKey("smile")
if ok {
list.Print()
}
list, ok = iic.GetIndexesByKey("hello")
if ok {
list.Print()
}
//iic.DeleteByID(MyInt(1))
fmt.Println(iic.GetKeysByID(MyInt(1)))
}
type Comparable[T any] interface {
Compare(T) int
}
type Node[T any] struct {
next *Node[T]
Value Comparable[T]
}
type List[T any] struct {
head *Node[T]
Number int
}
func NewList[T Comparable[T]]() *List[T] {
return &List[T]{&Node[T]{}, 0} // 头结点不存值
}
func (list *List[T]) Insert(value Comparable[T]) {
n := &Node[T]{Value: value}
prev, cur := list.head, list.head.next
for cur != nil && cur.Value.Compare(n.Value.(T)) <= 0 {
prev = cur
cur = cur.next
}
n.next = prev.next
prev.next = n
list.Number++
}
type MyInt int
func (m MyInt) Compare(m1 MyInt) int {
return int(m - m1)
}
func (list *List[T]) Delete(value T) {
head := list.head
//for head != nil { // 头结点存储值时
// if head.Value != value {
// break
// }
// head = head.next
//}
prev, cur := head, head.next
for cur != nil {
if cur.Value.Compare(value) == 0 {
prev.next = cur.next
list.Number--
} else {
prev = cur
}
cur = cur.next
}
}
func (list *List[T]) Update(oldValue, newValue Comparable[T]) {
for cur := list.head; cur != nil; cur = cur.next {
if cur.Value == oldValue {
cur.Value = newValue
}
}
}
func (list *List[T]) Search(value T) (exist bool) {
for cur := list.head.next; cur != nil; cur = cur.next {
if cur.Value.Compare(value) == 0 {
return true
}
}
return false
}
func (list *List[T]) Print() {
fmt.Print("[ ")
for head := list.head; head != nil; head = head.next {
//if head.Value != nil {
fmt.Print(head.Value, " ")
//}
}
fmt.Println("]")
}