Let's say I have an array with these values:
int foo [5] = { 1, 2, 3, 4, 5 };
I would like to compare the values inside the array by randomly picking two values from it at each step until nothing is left (or just one value in this case).
For example, at the start 1 and 4 are picked.
//Do stuff...
Then I want to remove them from the array and pick two other numbers etc., 2 and 5 for instance. Then the only remaining number is 3 which means the end of the algorithm.
Does anyone have a suggestion on how to do that kind of stuff ?
An array has a fixed size so you can't remove elements. You could mark a value as "deleted" by giving it some special value.
To really remove elements you better use a vector
@Thomas1965 I see, well I could also use a vector as you suggest. Thank you !
@tpb This was just an example but no, values won't be consecutive. Thank you very much for this piece of code, that will help me continuing what I'm doing.
int v[] { 1, 2, 3, 4, 5 }; // Your data
int sz = sizeof v / sizeof *v;
shuffle(begin(v), end(v), rng); // "pick randomly"
for (int i = 0; i < sz - 1; ) {
int a = v[i++];
int b = v[i++];
cout << a << ", " << b << '\n';
}
5, 3
4, 2
On that run, at the start 5 and 3 were picked.
Then 4 and 2 were picked.
The 1 was left unused, for no pair was left for it.