Comparing values from array

Hello everyone,

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 ?

Thanks in advance !

You could shuffle it and then take the elements two at a time in order.

Is this, perchance, an array of consecutive values as you've shown?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
using namespace std; // not recommended

int main() {
    long unsigned seed = chrono::high_resolution_clock
                               ::now().time_since_epoch().count();
    default_random_engine rng(seed);

    int v[] { 7, 3, 5, 8, 4, 0, 2, 1, 6 };
    int sz = sizeof v / sizeof *v;

    shuffle(begin(v), end(v), rng);

    for (int i = 0; i < sz - 1; ) {
        int a = v[i++];
        int b = v[i++];
        cout << a << ", " << b << '\n';
    }
}

Last edited on
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.
You did miss the point of the shuffle:
1
2
3
4
5
6
7
8
9
10
    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.
Topic archived. No new replies allowed.