Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. // an array of bitmap uint64_t.
  8.  
  9. // bit 0 of bitmap[0] represents page 0.
  10. // bit 0 of bitmap[1] represents page 64.
  11.  
  12. // array size 4096
  13.  
  14. // 1 - page is marked for use
  15. // 0 - page is available for use
  16.  
  17. // Allocation()
  18. // input: bitmap, size, n
  19. // n contiguous pages
  20. // returns: index of the first page of the allocation
  21.  
  22. // 0010001110010
  23.  
  24. // n=3. Result: page no. 3
  25. // n=4. Result: -1
  26. // n=2. Result: 0
  27.  
  28.  
  29. // n = 80
  30.  
  31. #define BITMAP_SIZE 4096
  32. #define BIT_SIZE 64
  33.  
  34.  
  35. class Solution {
  36.    
  37.     vector<uint64_t> bitmap(BITMAP_SIZE, 0);
  38. public:
  39.     int alloc(int reqrd_pages) {
  40.         int matches = 0;
  41.         int start = -1;
  42.         for (int i = 0; i < BITMAP_SIZE; i++) { // bitmap[0] = 0010001110010 j =  
  43.             for (int j = 0; j < BIT_SIZE; j++) {
  44.                 if(bitmap[i] >> j) & 0x1)
  45.                     continue;
  46.                 if (start < 0)
  47.                     start = j;
  48.                 while (j < BIT_SIZE && !((bitmap[i] >> j) & 0x1) && matches < reqrd_pages) { // bitmap[0] = 0000000000000 bitmap[1] = 0000000000000
  49.                     j++; // 2
  50.                     matches++; // 2
  51.                 }
  52.                 if (matches != reqrd_pages) {
  53.                     if (j < BIT_SIZE)
  54.                         matches = 0;
  55.                     continue;
  56.                 }
  57.                 j = start; // 0
  58.                 matches = 0; // 0
  59.                 while (j < BIT_SIZE && !((bitmap[i] >> j) & 0x1) && matches < reqrd_pages) {
  60.                     bitmap[i] |= 1 << j; // // bitmap[i] = 0010001110011
  61.                     j++; // 2
  62.                     matches++; // 2
  63.                 }
  64.                 return (i * BIT_SIZE) + start + 1;
  65.             }
  66.         }
  67.     }
  68.     return -1;
  69. };
  70.  
  71.  
  72. int main() {
  73.    
  74.    
  75.    
  76.     Solution sol;
  77.     n = 3
  78.     int result = sol.alloc(3);
  79.     cout << result;
  80.    
  81.    
  82.     cout<<"Hello World";
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement