title: LRU Page Replacement algorithm C#
body: <p>I am trying to write a function which simulates LRU page replacement. I understand LRU pretty well but am having problems coding it. The following things are being passed into the LRU function. The user specifies the 20 character reference string of #'s 1-9 which is stored in an array called refString of size 20. The number of frames the user enters (1-7) is stored in a variable numFrames. Finally, an array of size 7 called frame is passed in.</p>
  
  <p>Here is the code I have, and I am getting a close number but not quite. Maybe someone can help out!</p>
  
  <pre><code>private static void LRU(int numFrames, int[] refString, int[] frame)
  {
      int i, j = 0, k, m, flag = 0, count = 0, top = 0;
  
      for (i = 0; i &lt; 20; i++)
      {
          for (k = 0; k &lt; numFrames; k++)
          {
              if (frame[k] == refString[i])
              {
                  flag = 1;
                  break;
              }
          }
  
          if (j != numFrames &amp;&amp; flag != 1)
          {
              frame[top] = refString[i];
              j++;
  
              if (j != numFrames)
              {
                  top++;
              }
          }
  
          else
          {
              if (flag != 1)
              {
                  for (k = 0; k &lt; top; k++)
                  {
                      frame[k] = frame[k + 1];
                  }
  
                  frame[top] = refString[i];
              }
  
              if (flag == 1)
              {
                  for (m = k; m &lt; top; m++)
                  {
                      frame[m] = frame[m + 1];
                  }
  
                  frame[top] = refString[i];
              }
          }
  
          if (flag == 0)
          {
              count++;
          }
          else
          {
              flag = 0;
          }
  
      }
  
      Console.WriteLine("\nThe number of page faults with LRU is: " + count);
  }
  </code></pre>