# Complicated Condition

This is a discussion on Complicated Condition within the C++ Programming forums, part of the General Programming Boards category; Hi. I have a problem that I could not figure out. I have these datasets read from a textfile (1 ...

1. ## Complicated Condition

Hi. I have a problem that I could not figure out. I have these datasets read from a textfile (1 to N):

a1 b1
a2 b2
a3 b3
:
:
aN bN

I need to make this:

If 'a' have the same value, calculate the average of 'b'.
E.g: if a1 & a3 are the same value, than calculate (b1+b3)/2
or if a1=a3=a4=a10, then calculate the average of (b1+b3+b4+b10)/4

Thanks.Hope somebody out there can give me some ideas on this.

zmi

2. What's your best idea?

3. Originally Posted by Daved
What's your best idea?
I set the 'a' value and set a condition.But, this only calculate the average for the particular condition only.E.g: If I set a==60,then it will print average of 'b' if a==60. It did not work if there is multiple condition.
p/s: 'a' actually is the angle between 0 to 90 degrees.
Here is the sample of the code:

Code:
```for(i=0;i<n;i++){
fscanf(fin,"%f,%f\n",&a[i],&b[i]);
}

for(i=0;i<n;i++){

if (a[i]==60){
k=k+1;
sum=sum+b[i];
}
}
printf("%.1f\n",sum/k);```
or something like this:

Code:
```while (!feof(fin)){
fscanf(fin,"%f,%f\n",&a,&b);

if (a==60){
sum=sum+b;
k=k+1;
printf("%.1f\n",sum/k);
}

}```

4. I set the 'a' value and set a condition.But, this only calculate the average for the particular condition only.E.g: If I set a==60,then it will print average of 'b' if a==60. It did not work if there is multiple condition.
What do you mean?

Here's an idea: read in the input as a list of pairs. Sort the list of pairs according to the "a" values. Now, you just need to traverse over the list once, taking advantage of the fact that all the pairs with the same "a" values will be grouped together.

By the way, is this C or C++?

5. Thank you for the idea.I managed to sort the data. Now I'm having trouble to calculate the average of 'b' (sum/k).
I got the sum, but don't know how to calculate the k value.

Here's the code to calculate the sum:

Code:
```for(i=0; i<n; i++){

for(j=i+1; j<n; j++){

if(a[i] == a[j])
{
k=k+1;
sum[i]=b[i]+b[j];
}

}
printf("%.1f %.3f %.1f %d\n",a[i],b[i],sum[i],k);
}```
This is sample of dataset I used (a,b):

60,10
70,11
80,20
60,25
70,30
60,14
80,20

This is the output (a,b,sum,k):

60.0 10.000 24.0 1
60.0 25.000 39.0 2
60.0 14.000 0.0 2
70.0 30.000 41.0 3
70.0 11.000 0.0 3
80.0 20.000 40.0 4
80.0 20.000 0.0 4

Popular pages Recent additions