Given the trace program below. I basically need to store a 1 or a 0 to the corresponding a[r[i]]
the problem is I need to be able to keep track of the index of vectors zero and one to check the last index that was used for each vector.
For example:
// the values of vector zero and one after reading the file
zero = { 0, 0, 0, 0, 0};
one = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
Four random numbers
2, 4, 16, 12
ave = 14. 50
(2) a[r[i]] < 14.50
a[r[i]] = zero[0];
(4) a[r[i]] < 14.50
a[r[i]] = zero[1];
(16) a[r[i]] < 14.50
a[r[i]] = one[0];
(12) a[r[i]] < 14.50
a[r[i]] = zero[2];
Four random numbers
15, 36, 48, 45
ave = 35
(15) a[r[i]] < 35
a[r[i]] = zero[3];
(36) a[r[i]] < 35
a[r[i]] = one[1];
(48) a[r[i]] < 35
a[r[i]] = one[2];
(45) a[r[i]] < 35
a[r[i]] = one[3];
My initial attempt to solve the problem
int countZero = 0;
int countOne = 0;
for( int i = 0; i < 4; ++i )
{
if( a[r[i]] < ave )
{
if( !one.empty() )
{
a[r[i]] = zero[countZero];
countZero++;
}
else
// if there are no more available values retain the same value
a[r[i]] = a[r[i]];
}
else
{
if( !one.empty() )
{
a[r[i]] = one[countOne];
countOne++;
}
else
// if there are no more available values retain the same value
a[r[i]] = a[r[i]];
}
cout << a[r[i]] << " ";
}
cout << "\n";
The code above only works for the first four numbers. The succeding random numbers are not replace with 1s and 0s but the values are retained.
Sample Output:
// correct
2 4 16 12
0 0 1 0
// the values are retained
15 36 48 45
15 36 48 45
// should be
15 36 48 45
0 1 1 1
Any tips on how to solve this?