Advertisement
Guest User

Untitled

a guest
Jan 13th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. # define N 10
  3. double TotalAvg(int a[]);
  4. double UpdateAvg(int a[], double avg, int number, char op, int index);
  5. int FindBestPartition(int a[]);
  6. int main()
  7. {
  8.      int i=0, partition=-1;
  9.      int a[N] = {0};
  10.      printf("Please enter %d elements to find their best partition:\n", N);
  11.      for(i=0; i<N; i++)
  12.      {
  13.          scanf("%d", &a[i]);
  14.      }
  15.      partition = FindBestPartition(a);
  16.      printf("Best partition for the given array is at index: %d\n", partition);
  17.      return 0;
  18. }
  19.  
  20. double TotalAvg(int a[])
  21. {
  22.     /*sum=the value of all the index in the array, index for the for*/
  23.     double sum=0;
  24.     int i;
  25.     for(i=0;i<N;i++)
  26.     sum+=a[i];
  27.     return sum/N;
  28. }
  29. /*עבור + מעדכנת את הממוצע עם הוספת איבר חדש*/
  30. /*עבור - מעדכנת את הממוצע על החסרת איבר*/
  31. /*if op=- and number=0 the function return that the update avg is 0*/
  32. double UpdateAvg(int a[], double avg, int number, char op, int index)
  33. {
  34.     if(op=='+')
  35.     {
  36.         return ((avg*number+(double)a[index])/(double)(number+1));
  37.     }
  38.     else
  39.     {
  40.        if(number==1)return 0;
  41.        return ((avg*number-(double)a[index])/(double)(number-1));
  42.     }
  43. }
  44. int FindBestPartition(int a[])
  45. {
  46.     /*max הוא האינדקס עבורו ההפרש מקסימלי*/
  47.     /*avgR=average of the right side,avgL=average of left side*/
  48.     /*index=האיבר עבורו ההפרש הכי גדול*/
  49.     /*הפעולה מוצאת את ההפרש המקסימלי בין ממוצע שמאל לממוצע ימין ומחיזרה את האינדקס שבוא זה מתרחש*/
  50.     /*בלולאה אני מעדכן את ממוצע ימין וממצו שמאל באזרת הפונקציה UpdateAvg*/
  51.     int i=0,index=0;
  52.     double avgR=UpdateAvg(a,TotalAvg(a),N,'-',0),avgL=a[0],max,hefresh;
  53.     hefresh=avgL-avgR;
  54.     if(hefresh<0)hefresh=hefresh*(-1);
  55.     max=hefresh;
  56.     for(i=1;i<N;i++)
  57.     {
  58.         avgL=UpdateAvg(a,avgL,i,'+',i);
  59.         avgR=UpdateAvg(a,avgR,N-i,'-',i);
  60.         hefresh=avgL-avgR;
  61.         if(hefresh<0)hefresh=hefresh*(-1);
  62.         if(hefresh>max)
  63.         {
  64.             max=hefresh;
  65.             index=i;
  66.         }
  67.     }
  68.     return index;
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement