mbah_bejo

modus (recursive)

Dec 8th, 2020 (edited)
964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. int cari_modus(int arr[], int mode[], int posNow, int size, int k, int *n){
  6.     int countA=0, countB=0;
  7.     printf("now = %d\n",posNow);
  8.     while (posNow == arr[k]){
  9.         countA++;
  10.         k++;
  11.         if (k == size)
  12.         {
  13.             mode[*n] = arr[k-1];
  14.             return countA;
  15.         }
  16.     }
  17.     countB = cari_modus(arr, mode, arr[k], size, k, n);
  18.     printf("count1 (%d)= %d count2 (%d)= %d\n",arr[k-1], countA, arr[k], countB);
  19.     if (countA > countB) {
  20.         printf("%d > %d\n", countA, countB);
  21.         if(*n!=0 && mode[*n-1]!=arr[k-1]){
  22.             mode[*n-1] = arr[k-1];
  23.         }
  24.         mode[*n] = arr[k-1];
  25.         printf("mode[%d] = %d\n", *n, mode[*n]);
  26.     }
  27.     else if (countA < countB){
  28.         printf("%d < %d\n", countA, countB);
  29.         printf("mode[%d] = %d\n", *n, mode[*n]);
  30.         return countB;
  31.     }
  32.     else if (countA == countB){
  33.         printf("%d = %d\n", countA, countB);
  34.         cout<< *n<<mode[*n];
  35.         if(*n==0 && mode[*n]==0){
  36.            
  37.             mode[*n] = arr[k-1];
  38.         }
  39.         else
  40.         {
  41.         mode[++*n] = arr[k-1];
  42.         }
  43.         printf("mode[%d] = %d\n", *n, mode[*n]);
  44.     }
  45.     return countA;
  46. }
  47.  
  48. int main(){
  49.     int a[] = {1,1,2,3,3,3,3,3,4,4,4,5,5,5,5,5};
  50.     // int a[] = {1};
  51.     // int a[] = {1,2,1,2,3};
  52.     // int a[] = {1,5,1,1,3};
  53.     int ukuran = sizeof(a) / sizeof(a[0]);
  54.     sort(a,a+ukuran);
  55.     if (ukuran == 1) cout<< a[0];
  56.     else{
  57.     int n=0;
  58.     int modus[5] ={0};
  59.     cari_modus(a, modus,a[0], ukuran, 0, &n);
  60.     n=0;
  61.     while (modus[n] != 0){
  62.         cout << "mode = "<< modus[n]<< "\n";
  63.         n += 1;
  64.     }  
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment