최적 캐싱


14

일련의 메모리 요청과 캐시 크기가 제공됩니다. 캐시 교체 전략에서 캐시 미스 수를 최소로 반환해야합니다.

최적의 전략은 Belady의 알고리즘으로 원하는 경우 사용할 수 있습니다.


캐싱 시스템은 다음과 같이 작동합니다. 캐시가 비어 있습니다. 메모리 요청이 들어옵니다. 요청이 캐시에 데이터 조각을 요청하면 모든 것이 정상입니다. 그렇지 않으면 캐시 누락이 발생합니다. 이 시점에서 나중에 사용하기 위해 요청 된 데이터를 캐시에 삽입 할 수 있습니다. 캐시가 가득 차서 새 데이터를 삽입하려면 이전에 캐시에 있던 데이터를 제거해야합니다. 캐시에만 있지 않은 데이터는 절대 삽입 할 수 없습니다.

목표는 주어진 메모리 요청 순서 및 캐시 크기에 대해 가능한 최소 캐시 누락 수를 찾는 것입니다.


캐시 크기, 양의 정수 및 토큰 목록 인 메모리 요청 시퀀스가 ​​제공됩니다. 이 토큰들은 적어도 256 개의 다른 토큰이 가능하다면 (바이트는 괜찮고, bool은 그렇지 않습니다) 원하는 토큰 종류가 될 수 있습니다. 예를 들어, 정수, 문자열, 목록은 모두 괜찮습니다. 필요한 경우 설명을 요청하십시오.


테스트 사례 :

3
[5, 0, 1, 2, 0, 3, 1, 2, 5, 2]

6

이를 달성하는 대체 정책 은 wikipedia 를 참조하십시오 .

2
[0, 1, 2, 0, 1, 0, 1]

3

2캐시에 추가하지 마십시오 .

3
[0, 1, 2, 1, 4, 3, 1, 0, 2, 3, 4, 5, 0, 2, 3, 4]

9

이것을 달성하는 한 가지 방법은 결코 축출되지 것입니다 02및 퇴거 1마지막으로 사용한 후 가능한 한 빨리.


득점 : 이것은 코드 골프입니다. 가장 적은 바이트가 이깁니다.


목록에 2 개 이상의 토큰이 있다고 가정 할 수 있습니까?
Arnauld

@Arnauld 아니요라고 대답 할 것입니다. 단 하나의 솔루션 만 있다면 대답은 항상 1입니다.
isaacg

답변:


4

JavaScript (ES6), 128 바이트

로 입력을 (size)(list)받습니다.

s=>a=>a.map((x,i)=>c.includes(x)?0:c[e++,[x,...c].map(m=(x,j)=>(k=[...a,x].indexOf(x,i+1))<m||(p=j,m=k)),i<s?i:p-1]=x,e=c=[])&&e

온라인으로 사용해보십시오!

댓글

이것은 Belady 알고리즘의 구현입니다.

s => a =>                      // s = cache size; a[] = token list
  a.map((x, i) =>              // for each token x at position i in a[]:
    c.includes(x) ?            //   if x is currently stored in the cache:
      0                        //     do nothing
    :                          //   else:
      c[                       //     update the cache:
        e++,                   //       increment the number of errors (cache misses)
        [x, ...c]              //       we want to find which value among x and all current
                               //       cache values will be needed for the longest time in
                               //       the future (or not needed anymore at all)
        .map(m =               //       initialize m to a non-numeric value
                 (x, j) =>     //       for each x at position j in this array:
          ( k = [...a, x]      //         k = position of x in the array made of all values
            .indexOf(x, i + 1) //         of a[] followed by x, starting at i + 1
          ) < m                //         if it's greater than or equal to m, or m is
          || (p = j, m = k)    //         still non-numeric: set p to j and m to k
        ),                     //       end of inner map()
        i < s ?                //       if i is less than the cache size:
          i                    //         just fill the cache by using the next cache slot
        :                      //       else:
          p - 1                //         use the slot that was found above
                               //         special case: if p = 0, x was the best candidate
                               //         and we're going to store it at c[-1], which is
                               //         simply ignored (it will not trigger c.includes(x))
      ] = x,                   //     store x at this position
      e = c = []               //     start with e = [] (coerced to 0) and c = []
  ) && e                       // end of outer map; return e

4

펄 5 , 193 바이트

sub g{
  my($i,$m,$s,@a,%c)=(-1,0,@_);
  for(@a){
    $i++;
    next if $c{$_}++ || ++$m && keys%c <= $s;
    my($x,$d);
    for $k (sort keys %c){  #find which to delete, the one furtherst away
      my $n=0;
      ++$n && /^$k$/ && last for @a[$i+1..$#a];
      ($x,$d)=($n,$k) if $n>$x
    }
    delete $c{$d}
  }
  $m
}

온라인으로 사용해보십시오!

print g(3,  5, 0, 1, 2, 0, 3, 1, 2, 5, 2),"\n";                     # 6
print g(2,  0, 1, 2, 0, 1, 0, 1),"\n";                              # 3
print g(3,  0, 1, 2, 1, 4, 3, 1, 0, 2, 3, 4, 5, 0, 2, 3, 4),"\n";   # 9

들여 쓰기, 줄 바꿈, 공백, 주석없이 193 바이트 :

sub g{my($i,$m,$s,@a,%c)=(-1,0,@_);for(@a){$i++;next if$c{$_}++||++$m&&keys%c<=$s;my($x,$d);for$k(sort keys%c){my$n=0;++$n&&/^$k$/&&last for@a[$i+1..$#a];($x,$d)=($n,$k)if$n>$x}delete$c{$d}}$m}


1

하스켈 , 82 바이트

f n|let(d:t)#c=1-sum[1|elem d c]+minimum[t#take n e|e<-scanr(:)(d:c)c];_#_=0=(#[])

온라인으로 사용해보십시오!

설명

무차별 대입 : 모든 캐시 전략이 시도되고 최상의 결과가 반환됩니다.

f n            Define a function f on argument n (cache size) and a list (implicit).
 |let(d:t)#c=  Define binary helper function #.
               Arguments are list with head d (current data) and tail t (remaining data), and list c (cache).
 1-            It returns 1 minus
 sum[1|        1 if
 elem d c]+    d is in the cache, plus
 minimum[      minimum of
 t#            recursive calls to # with list t
 take n e|     and cache being the first n values of e, where
 e<-           e is drawn from
 scanr(:)  c]  the prefixes of c
 (d:c)         with d and c tacked to the end.
 ;_#_=0        If the first list is empty, return 0.
 =(#[])        f then calls # with the list argument and empty cache.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.