Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "container/list"
  5. "fmt"
  6. "math/rand"
  7. "time"
  8. )
  9.  
  10. type Storage interface {
  11. Get(int) int
  12. }
  13.  
  14. type LowSpeedStorage struct {
  15. Storage
  16. }
  17.  
  18. type LruCache struct {
  19. LowSpeedStorage
  20. capacity int
  21. }
  22.  
  23. type MyLruCache struct {
  24. LruCache
  25. capacity int
  26. dq *list.List
  27. cacheMap map[int]*list.Element
  28. }
  29.  
  30. func NewLruCache(cap int) *LruCache {
  31. return &LruCache{
  32. capacity: cap,
  33. }
  34. }
  35.  
  36. func NewMyLruCache(cap int) *MyLruCache {
  37. return &MyLruCache{
  38. capacity: cap,
  39. cacheMap: make(map[int]*list.Element, 0),
  40. dq: list.New(),
  41. }
  42. }
  43.  
  44. func (low *LowSpeedStorage) Get(k int) int {
  45. v := rand.Int()
  46. time.Sleep(1 * time.Second)
  47. return v
  48. }
  49.  
  50. func (lru *LruCache) Get(k int) int {
  51. return lru.LowSpeedStorage.Get(k)
  52. }
  53.  
  54. func (lru *MyLruCache) Get(k int) int {
  55. if v, ok := lru.cacheMap[k]; ok {
  56. // cache hit, move ele to front
  57. fmt.Printf("cache hit, move key: %d to front\n", k)
  58. lru.dq.MoveToFront(v)
  59. return v.Value.(int)
  60. }
  61. v := lru.LruCache.Get(k)
  62. if lru.dq.Len() == lru.capacity {
  63. last := lru.dq.Back()
  64. fmt.Printf("dq is full, remove last ele: %d\n", last.Value)
  65. lru.dq.Remove(last)
  66. }
  67. // add new ele to cache
  68. lru.dq.PushFront(k)
  69. lru.cacheMap[k] = lru.dq.Front()
  70. return v
  71. }
  72.  
  73. func (lru *MyLruCache) PrintAll() {
  74. for e := lru.dq.Front(); e != nil; e = e.Next() {
  75. fmt.Println(e.Value)
  76. }
  77. }
  78.  
  79. func main() {
  80. myLru := NewMyLruCache(4)
  81. myLru.Get(1)
  82. myLru.Get(2)
  83. myLru.Get(3)
  84. myLru.Get(1)
  85. myLru.Get(4)
  86. myLru.Get(5)
  87. myLru.PrintAll()
  88. return
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement