Arrange Binary in Order

I have this program which generates four unique random numbers from array a[]. Each random number is compared to the average.
If the value is < average
replace the value with 0 otherwise 1.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172`` ``````srand(time(NULL)); // 1D array int a[] = { 20, 30, 40, 27, 19, 8, 10, 17, 2, 9, 7, 15, 4, 8, 12, 6, 5, 10, 15, 6, 12, 3 }; int random[4]; //sum of four random numbers double sum2 = 0; //sum of a[] double sum = 295; unordered_set< int > unique; unordered_set< int >::iterator it; while( unique.size() < 4 ) { //generate four random numers from array a[] random[unique.size()] = rand() % 22; unique.insert( a[random[unique.size()]] ); } //display index for array a[] for(int i = 0; i < 4; ++i) { cout << "Index " << random[i] << "\n"; } cout << "\n"; cout << "4 Random Numbers " << "\n"; //display four random numbers from array a[] for( it = unique.begin(); it != unique.end(); ++it ) { cout << *it << " "; sum2 += *it; } cout << "\n"; double average; average = ( sum - sum2 ) / 18; cout << "Binary Values " << "\n"; int i = 0; for( it = unique.begin(); it != unique.end(); ++it, ++i ) { // if value from a[] is less than average replace the value with // 0 otherwise 1 if( *it < average ) a[random[i]] = 0; else a[random[i]] = 1; //display 1s and 0s cout << a[random[i]] << " "; } cout << "\n"; cout.setf(ios::fixed); cout << "Sum " << (int)sum << " Sum Random " << (int)sum2 << setprecision(2) << " Average " << average << "\n" << "\n"; //display values of a[] with 1s and 0s for(int i = 0; i < 22; ++i) { cout << a[i] << " "; } cout << "\n"; return 0; ``````

Sample Output
 ``123456789101112131415`` ``````// index use for array a[]..a[11],a[17]... Index 11 Index 17 Index 20 Index 7 4 Random Numbers //the values from a[] 10 12 15 17 Binary values 0 0 1 1 Sum 295 Sum Random 54 Average 13.39 20 30 40 27 19 8 10 1 2 9 7 0 4 8 12 6 5 0 15 6 1 3 ``````

Expected Output
 ``1234`` ``````20 30 40 27 19 8 10 1 2 9 7 0 4 8 12 6 5 0 15 6 1 3 //the array above should be the one below 20 30 40 27 19 8 10 1 2 9 7 1 4 8 12 6 5 0 15 6 0 3 ``````

The problem is some of the 1s and 0s are out of order.

Any ideas on how to fix this?
Why are you using 18 on line 41? Shouldn't you use sizeof( a ) instead of a hard-coded value?
there are 22 values in the array minus the 4 random numbers which is 18
Nvm what I said first. I ran the code myself and the output was actually correct:

 ``123456789101112`` ``````Index 11 Index 17 Index 20 Index 7 4 Random Numbers 15 10 12 17 Binary Values 1 0 0 1 Sum 295 Sum Random 54 Average 13.39 20 30 40 27 19 8 10 1 2 9 7 1 4 8 12 6 5 0 15 6 0 3``````

Somehow the order of your random numbers gets changed and therefor the wrong stuff gets swapped out. I did have to hardcore my values to simulate your exact situation though, so an error might occur while generationg the list.
Last edited on