๋ฌธ์ ๐ฝ
https://school.programmers.co.kr/learn/courses/30/lessons/17680
๋ค๋ฅธ์ฌ๋ ํ์ด ๐ฝ
function solution(cacheSize, cities) {
const MISS = 5, HIT = 1;
if (cacheSize === 0) return MISS * cities.length;
let answer = 0,
cache = [];
cities.forEach(city => {
city = city.toUpperCase();
let idx = cache.indexOf(city);
if (idx > -1) {
cache.splice(idx, 1);
answer += HIT;
} else {
if (cache.length >= cacheSize) cache.shift();
answer += MISS;
}
cache.push(city);
});
return answer;
}
๋ดํ์ด๐ฝ
1. ์ฑ๊ณต โญ
function solution(cacheSize, cities) {
let answer = 0;
let cache = []
// ex) ["newyork", "korea" ... ]
cities.map((city)=> city.toLowerCase()).forEach((city)=>{
// ์บ์์ ์ ์ฅ ๋์ด ์๋ค๋ฉด
if(cache.includes(city)){
// ์คํ์๊ฐ
answer+=1;
// stack ์กฐ์
// ํด๋น city ๋บ๋ค
cache = cache.filter((t)=> t!==city)
// ๋งจ์์ผ๋ก city ๋์ด์ค๋ค
cache.unshift(city);
}else{
// ์คํ์๊ฐ
answer+=5;
// stack ์กฐ์
// ๋งจ์์ผ๋ก city ๋์ด์ค๋ค.
cache.unshift(city);
}
cache=cache.filter((val,index) => index<=cacheSize-1)
})
return answer;
}
๋๋์ ๐ฝ
์ฒ์์ ์บ์๊ต์ฒด ์๊ณ ๋ฆฌ์ฆ์ ๋ํ ๋ฐฐ๊ฒฝ ์ง์์ด ์์ด์ ์์ฒญ ์ ๋จน์๋ค.
LRU(Least Recently Used) ๋ํ ๊ฐ๋ ์ ์ฐพ์๋ณด๊ณ cache hit ์ cache miss์ ๋ํด ์ ์ ์์๋ค.
ํด๋น ๊ฐ๋ ์ ๋ํ ์ดํด๋ฅผ ํ๊ณ ๋๋ค ์๊ณ ๋ฆฌ์ฆ์ ์ฝ๊ฒ ์งค ์ ์์๋ค.