Advertisement
100hahahaha

Untitled

May 11th, 2023
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. using namespace std;
  5.  
  6. void bubbleSort(int arr[], int n) {
  7.   for (int i = 0; i < n - 1; i++) {
  8.     for (int j = 0; j < n - i - 1; j++) {
  9.       if (arr[j] > arr[j+1]) {
  10.         swap(arr[j], arr[j+1]);
  11.       }
  12.     }
  13.   }
  14. }
  15.  
  16. int countOnes(int num) {
  17.   int cnt = 0;
  18.   while (num > 0){
  19.     cnt += num & 1;
  20.     num >>= 1;
  21.   }
  22.   return cnt;
  23. }
  24.  
  25. int main() {
  26.   srand(time(NULL));
  27.  
  28.   int n, percent;
  29.   cout << "Enter the size of the binary number: ";
  30.   cin >> n;
  31.   cout << "Enter the percentage of ones in the binary number: ";
  32.   cin >> percent;
  33.  
  34.   int ones = (n * percent) / 100;
  35.   int zeroes = n - ones;
  36.  
  37.   int arr[n];
  38.   for (int i = 0; i < ones; i++) {
  39.     arr[i] = 1;
  40.   }
  41.   for (int i = ones; i < n; i++) {
  42.     arr[i] = 0;
  43.   }
  44.  
  45.   // shuffle the array
  46.   for (int i = n-1; i >= 0; i--) {
  47.     int j = rand() % (i+1);
  48.     swap(arr[i], arr[j]);
  49.   }
  50.  
  51.   cout << "Before sorting, the binary number is: ";
  52.   for (int i = 0; i < n; i++) {
  53.     cout << arr[i];
  54.   }
  55.   cout << endl;
  56.  
  57.   bubbleSort(arr, n);
  58.  
  59.   cout << "After sorting, the binary number is: ";
  60.   for (int i = 0; i < n; i++) {
  61.     cout << arr[i];
  62.   }
  63.   cout << endl;
  64.  
  65.   cout << "The number of ones in the binary number is: " << countOnes(arr[n-1]) << endl;
  66.  
  67.   return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement