dimanche 21 janvier 2018

Find nearest number in vector with conditions

Let's say I have a vector like this:

std::vector<int> inputs = {3,2,6,3,7,1,8};
int left = 1; // Number 3
int right = 4; // Numbers 2,6,3,7
int middle = 2; // Numbers 1,8

Now for every number in 'middle' (1, 8), I'd like to find out what's the nearest GREATER number in vector 'left side, and right side'. If there is no greater number, return nearest SMALLER number.

// Iterating the last two numbers 1, and 8.
for(int i = left+right; i<left+right+middle; i++{
   ...
  }

I have tried getting the nearest GREATER element with the std::lower_bound, but it always returns some number. Even if there is no greater or equal element. Therefore I cannot proceed...

The output should look like:

closest-left, closest-right --> index in vector

3,2 --> index 0,1
3,7 --> index 0,4

Explanation of output:

The number nearest to 1 in the left side {3}, is 3, in the left side {2,6,3,7}, its 2.

The number nearest to 8 in the left side {3}, is 3, in the left side {2,6,3,7}, its 7.

What's the other way to approach this?

Aucun commentaire:

Enregistrer un commentaire