Advertisement
Sri27119

pageReplace_Optimal

Nov 25th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void getRefString(int *ref_string, int n)
  4. {
  5. printf("Enter reference string: ");
  6. for (int i = 0; i < n; i++)
  7. {
  8. scanf("%d", &ref_string[i]);
  9. }
  10. }
  11.  
  12. int findOptimalPage(int *frame, int frame_size, int *ref_string, int n, int current_index)
  13. {
  14. int farthest = current_index;
  15. int replace_index = -1;
  16.  
  17. for (int i = 0; i < frame_size; i++)
  18. {
  19. int j;
  20. for (j = current_index + 1; j < n; j++)
  21. {
  22. if (frame[i] == ref_string[j])
  23. {
  24. if (j > farthest)
  25. {
  26. farthest = j;
  27. replace_index = i;
  28. }
  29. break;
  30. }
  31. }
  32.  
  33. if (j == n)
  34. {
  35. return i;
  36. }
  37.  
  38. if (replace_index == -1)
  39. {
  40. replace_index = i;
  41. }
  42. }
  43.  
  44. return replace_index;
  45. }
  46.  
  47. int main()
  48. {
  49. int n;
  50. printf("Enter size of reference String: ");
  51. scanf("%d", &n);
  52. int ref_string[n];
  53. getRefString(ref_string, n);
  54. int frame_size;
  55. printf("Enter frame size: ");
  56. scanf("%d", &frame_size);
  57. int frame[frame_size];
  58. int hits = 0, page_faults = 0;
  59.  
  60. for (int i = 0; i < frame_size; i++)
  61. {
  62. frame[i] = -1;
  63. }
  64.  
  65. for (int i = 0; i < n; i++)
  66. {
  67. int found = 0;
  68.  
  69. // Check if page is already in frame
  70. for (int j = 0; j < frame_size; j++)
  71. {
  72. if (frame[j] == ref_string[i])
  73. {
  74. hits++;
  75. found = 1;
  76. break;
  77. }
  78. }
  79.  
  80. if (!found)
  81. {
  82. int empty_found = 0;
  83. // Check if there's an empty frame available
  84. for (int j = 0; j < frame_size; j++)
  85. {
  86. if (frame[j] == -1)
  87. {
  88. frame[j] = ref_string[i];
  89. page_faults++;
  90. empty_found = 1;
  91. break;
  92. }
  93. }
  94.  
  95. if (!empty_found)
  96. {
  97. // Find the page to replace using the optimal policy
  98. int pos = findOptimalPage(frame, frame_size, ref_string, n, i);
  99. frame[pos] = ref_string[i];
  100. page_faults++;
  101. }}}
  102.  
  103. double hit_ratio = (double)hits / n;
  104. double page_fault_ratio = (double)page_faults / n;
  105. printf("Hits: %d\n", hits);
  106. printf("Page Faults: %d\n", page_faults);
  107. printf("Hit Ratio: %f\n", hit_ratio);
  108. printf("Page Fault Ratio: %f\n", page_fault_ratio);
  109.  
  110. printf("Final frame state: ");
  111. for (int i = 0; i < frame_size; i++)
  112. {
  113. printf("%d ", frame[i]);
  114. }
  115. printf("\n");
  116.  
  117. return 0;
  118. }
  119.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement