-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
127 lines (103 loc) · 1.7 KB
/
Copy pathmain.go
File metadata and controls
127 lines (103 loc) · 1.7 KB
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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
const size = 5
type Node struct {
val string
left *Node
right *Node
}
type Queue struct {
Head *Node
Tail *Node
Length int
}
type Cache struct {
Queue Queue
Hash Hash
}
type Hash map[string]*Node
func NewCache() Cache {
return Cache{
Queue: NewQueue(),
Hash: Hash{},
}
}
func NewQueue() Queue {
head := &Node{}
tail := &Node{}
head.right = tail
tail.left = head
return Queue{
Head: head,
Tail: tail,
}
}
func (c *Cache) Check(str string) {
node := &Node{}
if val, ok := c.Hash[str]; ok {
node = c.Remove(val)
} else {
node = &Node{
val: str,
}
}
c.Add(node)
c.Hash[str] = node
}
func (c *Cache) Remove(n *Node) *Node {
fmt.Printf("Remove %s\n", n.val)
left := n.left
right := n.right
left.right = right
right.left = left
c.Queue.Length -= 1
delete(c.Hash, n.val)
return n
}
func (c *Cache) Add(n *Node) {
fmt.Printf("add:%s\n", n.val)
tmp := c.Queue.Head.right
c.Queue.Head.right = n
n.left = c.Queue.Head
n.right = tmp
tmp.left = n
c.Queue.Length++
if c.Queue.Length > size {
c.Remove(c.Queue.Tail.left)
}
}
func (c *Cache) Display() {
c.Queue.Display()
}
func (q *Queue) Display() {
node := q.Head.right
fmt.Printf("%d - [", q.Length)
for i := 0; i < q.Length; i++ {
fmt.Printf("{%s}", node.val)
if i < q.Length-1 {
fmt.Printf("<-->")
}
node = node.right
}
fmt.Println("]")
}
func main() {
fmt.Println("Start cache")
cache := NewCache()
for {
fmt.Print("Enter a word (or 'exit' to quit): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
if strings.ToLower(input) == "exit" {
break
}
cache.Check(input)
cache.Display()
}
}