hello
I'm trying to get the index of the smallest element of an array, IF this element index satisfies a condition in another array. explaining:
i have an int array and a bool array
int count[] = {0, 0, 0, 0};
bool avail[] = {true, true, true, true};
every iteration i choose the bools randomly. i want to get the smallest number in count[] which is also 'true' in avail[]. like in
count {10, 20, 30, 40}
avail {false, false, true, true}
should return 2 (third element of both arrays)
I got to this, but sometimes I get the index 0 even if it is false (it happens when the index 0 is smaller than the others). But I feel there must be a simpler way to do it...
oh, and every iteration I also increase count[] by one in the current choosen index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
#include <random>
#include <chrono>
int main(){
std::default_random_engine gen(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_int_distribution<int> dist(0, 1);
int count[] = {0, 0, 0, 0};
for(size_t i=0; i<100; i++){
bool avail[] = {true, true, true, true};
for (size_t n=0; n<sizeof(avail)/sizeof(avail[0]); n++){
avail[n] = dist(gen);
}
size_t choosen = 0;
for (size_t n=0; n<sizeof(count)/sizeof(count[0]); n++){
if (count[n] <= count[choosen] && avail[n] == true){
choosen = n;
}
}
count[choosen]++;
std::cout << "choosen: " << choosen << "\tTrue: " << avail[choosen] << std::endl;
}
for (size_t n=0; n<sizeof(count)/sizeof(count[0]); n++){
std::cout << count[n] << std::endl;
}
}
| |
possible output (what shouldn't happen is in bold)
choosen: 1 True: 1
choosen: 2 True: 1
choosen: 0 True: 1
choosen: 1 True: 1
choosen: 1 True: 1
choosen: 0 True: 0
choosen: 3 True: 1
choosen: 0 True: 0
choosen: 1 True: 1
choosen: 2 True: 1
choosen: 2 True: 1
choosen: 3 True: 1
choosen: 0 True: 1
choosen: 2 True: 1
choosen: 1 True: 1
choosen: 3 True: 1
choosen: 3 True: 1
choosen: 2 True: 1
choosen: 0 True: 0
choosen: 1 True: 1
choosen: 0 True: 1
25
25
25
25
|