Created
March 31, 2021 08:14
-
-
Save jakejakeho/4fed4cd22d01904e2db991b8054a9f7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <cmath> | |
#include <ctime> | |
#include <vector> | |
using namespace std; | |
template <typename T> | |
class Cache { | |
public: | |
struct CacheData{ | |
string key; | |
T value; | |
time_t lastAccessTime; | |
}; | |
static const int primeNum = 2039; | |
static const int maxSize = 5; | |
vector<CacheData> data[Cache::primeNum]; | |
CacheData* get(string key) { | |
int index = hashFunc(key); | |
for(CacheData cacheData : data[index]) { | |
if (cacheData.key == key) { | |
return &cacheData; | |
} | |
} | |
return NULL; | |
} | |
void put(string key, T value, double weight) { | |
int index = hashFunc(key); | |
int size = data[index].size(); | |
// Set value | |
for(CacheData cacheData : data[index]) { | |
if (cacheData.key == key) { | |
cout << "set Value" << endl; | |
cacheData.value = value; | |
return; | |
} | |
} | |
// Insert value | |
if ((size + 1) <= Cache::maxSize) { | |
CacheData cacheData; | |
cacheData.key = key; | |
cacheData.value = value; | |
cacheData.lastAccessTime = time(0); | |
data[index].push_back(cacheData); | |
cout << "push_back" << endl; | |
} else { // invalidate | |
int leastScoreIndex = 0; | |
double leastScore = LC_MAX; | |
for(int i = 0; i < data[index].size(); i++) { | |
double score = getScore(data[index][i], weight); | |
if (score < leastScore) { | |
cout << data[index][i].key << " score:" << score << endl; | |
leastScoreIndex = i; | |
leastScore = score; | |
} | |
} | |
cout << "invalidate key:" << data[index][leastScoreIndex].key << endl; | |
data[index][leastScoreIndex].key = key; | |
data[index][leastScoreIndex].value = value; | |
data[index][leastScoreIndex].lastAccessTime = time(0); | |
} | |
} | |
double getScore(CacheData cacheData, double weight) { | |
time_t currentTime = time(0); | |
if (currentTime != cacheData.lastAccessTime) { | |
return weight / log(currentTime / cacheData.lastAccessTime); | |
} else { | |
return weight / -100; | |
} | |
} | |
int hashFunc(string s) { | |
int total = 0; | |
for(char c: s) { | |
total += (int)c; | |
} | |
total %= primeNum; | |
return total; | |
} | |
}; | |
int main() { | |
Cache<int> cache; | |
cache.put("a", 1, 1.0); | |
cache.put("c", 1, 1.0); | |
cache.put("e", 1, 1.0); | |
cache.put("g", 1, 1.0); | |
cache.put("i", 1, 1.0); | |
cache.put("k", 1, 1.0); | |
if(cache.get("a") != NULL) | |
cout << cache.get("a")->key << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment