Nick
Nick

Reputation: 1056

What is the best way to loop through an array and find an array element closest to a key?

Here is my code so far and I am stuck. The closest value to 7 in terms of absolute value is 5. How can I check each element of the array to see if it is the closest element and then return that value. I know this is probably easier than I think but I am a beginner at programming.

#include <iostream>
#include <cmath>
using namespace std;

const int MAX = 25;

int searchArray(int [], int); \\prototype

int main(){

    int numArray[MAX] ={1,4,5,10,11,12,13,14,15,16,17,18,19,20,35,26,43,15,48,69,32,45,57,98,100};

searchArray(numArray, 7);
system("pause");
return 0;
}


int searchArray(int a[], int b){

int distance = 0;

for(int i=0;i<MAX;i++){
    if(i==b)
        return i;
    else if(i<b || i > b)
        abs(distance) == i-b;
    return distance;


}

}

Upvotes: 1

Views: 1385

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361642

You can use std::min_element as:

#include <iostream>
#include <algorithm>
#include <cstdlib>

int main()
{
   int numArray[] ={1,4,5,10,11,12,13,14,15,16,17,18,19,20,35,26,43,15,48,69,32,45,57,98,100};

   //find nearest element to key            
   int key = 7;
   auto cmp = [&](int a, int b) { return std::abs(key-a) < std::abs(key-b); };
   int nearest_value = *std::min_element(std::begin(numArray),std::end(numArray),cmp);

   std::cout << nearest_value << std::endl;
}

Output (demo):

5

Upvotes: 6

K-ballo
K-ballo

Reputation: 81379

You can use standard algorithms to do that for you:

struct closer_to
{
    int target_;

    explicit closer_to( int target ) : target_( target ){}

    bool operator ()( int left, int right ) const
    {
        return std::abs( target_ - left ) < std::abs( target_ - right );
    }
};

int* iter =
    std::min_element(
        numArray + 0, numArray + MAX
      , closer_to( 7 )
    );

min_element will return an iterator (pointer in this case) to the first element for which there is no other element in the Container that is closer_to( 7 ).

With C++11 and lambdas, it would look like this:

int* iter = 
    std::min_element(
        numArray + 0, numArray + MAX
      , []( int left, int right ) { return std::abs( target_ - left ) < std::abs( target_ - right ); }
    );

Upvotes: 3

sampson-chen
sampson-chen

Reputation: 47327

Write your search function to the following:

int searchArray(int a[], int b){

    int min_dist = 0; // keep track of mininum distance seen so far
    int min_index = 0; // keep track of the index of the element 
                       // that has the min index

    for( int i = 0; i < a.Length; i++ ){ // a.Length is the size of the array
        if( a[i] == b ) { // if we find the exact one, stop
            return i;
        } else { // otherwise, keep looking for the closest
            if ( abs(a[i] - b) < min_dist ) { // if this one is closer, update
                min_dist = abs(a[i] - b);
                min_index = i;
            }
        }
    }
    return min_index; // when we finish return the index of the closest
}

Upvotes: 3

imreal
imreal

Reputation: 10378

You have to compare your number to every number on your array and keep track of the smallest distance so far.

int searchArray(int a[], int b){
    int minDistance = -1;

    for(int i=0;i<MAX;i++){
        if(minDistance == -1 || abs(minDistance - b) > abs(a[i] - b))
            minDistance = a[i];
    }
    return minDistance;
}

Upvotes: 1

Related Questions