-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
134 lines (112 loc) · 1.9 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"errors"
"fmt"
)
type Sieve interface {
Evict() error
Add(value int) error
}
type Node struct {
value int
visited bool
next *Node
prev *Node
}
type Cache struct {
head *Node
tail *Node
hand *Node
size int
maxSize int
}
func NewCache(maxSize int) *Cache {
return &Cache{
head: nil,
tail: nil,
hand: nil,
size: 0,
maxSize: maxSize,
}
}
func (c *Cache) Add(value int) error {
if c.size == c.maxSize {
if err := c.Evict(); err != nil {
return err
}
}
newNode := &Node{value: value, visited: false}
if c.head == nil {
c.head = newNode
c.tail = newNode
} else {
newNode.next = c.head
c.head.prev = newNode
c.head = newNode
}
c.size++
return nil
}
func (c *Cache) Evict() error {
if c.size == 0 {
return errors.New("cache is empty")
}
if c.hand == nil {
c.hand = c.tail
}
for c.hand != nil {
if c.hand.visited {
c.hand.visited = false
c.hand = c.hand.prev
} else {
if c.hand.prev == nil && c.hand.next == nil {
c.head = nil
c.tail = nil
} else if c.hand.prev == nil {
c.head = c.hand.next
c.head.prev = nil
} else if c.hand.next == nil {
c.tail = c.hand.prev
c.tail.next = nil
} else {
c.hand.prev.next = c.hand.next
c.hand.next.prev = c.hand.prev
}
c.size--
return nil
}
}
return nil
}
func (c *Cache) Hit(value int) error {
node := c.head
for node != nil {
if node.value == value {
node.visited = true
return nil
}
node = node.next
}
return c.Add(value)
}
func (c *Cache) PrintCache() {
node := c.head
for node != nil {
fmt.Printf("Value: %d, Visited: %v\n", node.value, node.visited)
node = node.next
}
fmt.Println("\n")
}
func main() {
cache := NewCache(3)
cache.Hit(1)
cache.Hit(2)
cache.Hit(3)
cache.PrintCache()
cache.Hit(1)
cache.PrintCache()
cache.Hit(4)
cache.PrintCache()
cache.Hit(5)
cache.PrintCache()
}