Comparing and merging numbers

Hello everyone,

Let's say I have a file with this content:

6
8
9
12
15
20
22
30
I am comparing the first number with the others then the 2nd number with all the numbers below it etc.

For each comparison, I am looking if the two numbers are separated by less than 10 for example. Then I print all the numbers that respect this condition.

At this point I should have something like this:

6 8
6 9
6 12
6 15
8 9
8 12
8 15
9 12
9 15
12 15
12 20
12 22
15 20
15 22

But at the end, what I want as output is:

6 15
20 30

because I start from the beginning with 6 and the 'highest' value respecting the condition is 15 in this list. All numbers between 6 and 15 are ignored.
Same logic for 20 and 30 etc.

I tried to do something like that but it didn't go as expected.

int ans_a=,ans_b;
//...

int tempDiff = std::abs(number[j]-number[i]);
if(tempDiff <= 10 && (ans_a > number[i] || (ans_a == number[i] && ans_b < number[j]) ))
{
ans_a = number[i];
ans_b = number[j];
}

Any idea ?

Last edited on
This assumes the array is in order (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 <iostream>

int main() {
    int a[] = {6, 8, 9, 12, 15, 20, 22, 30};
    int size = sizeof a / sizeof a[0];
    
    for (int i = 0; i < size; ) {
        int k = i;
        for (int j = i + 1; j < size; j++)
            if (a[j] - a[i] <= 10)
                k = j;

        if (k != i) {
            std::cout << a[i] << ' ' << a[k] << '\n';
            i = k + 1;
        }
        else
            ++i;
    }

    return 0;
}

Last edited on
This works perfectly !
Thank you very much
Hmm I forgot to ask but by any chance, do you know how to also print the remaining numbers ?
In this example if we add 50 it would give:
6 15
20 30
50
Topic archived. No new replies allowed.