Go Down

Topic: Compare value to array (Read 667 times) previous topic - next topic

ThePoulsen

Hey all

Yet another noob question from me :)

I have the following array

Code: [Select]
int row [12] = {20, 30, 37, 50, 67, 83, 100, 117, 133, 167, 200, 233};

and a value

Code: [Select]
int val

Now I would like to compare the value to the array and find the best match for this, and read this out into a result integer.

Code: [Select]
int result

The readout should be the array position, and not the array value..

To clarify. if my "val" is 90, the one closest to this is 83 and this is in "row [5]". Therefore the value of "result" should be 5


sui

(not tested...)

Code: [Select]

int diff = 32767;           // save the lowest difference in this variable. init with maximum int because it's the worst possible match for this data type. don't know if there is a constant for maxint?
int result = 0;             // assuming the array contains only one element, the best match would allways be index #0

for (int i = 0; i<sizeof(row); i++) {             // loop trough array
  if ( abs( row[i] - val ) < diff )  {            // if the difference between value at index #i and val is lower than the previously found best match...
    result = i;                                   // save the better results index
    diff = abs( row[i] - val );                   // save the as yet best difference value
  }
}

Grumpy_Mike

So you have a loop that steps through all the array.
At each one you subtract the array element from the value and use the abs() function to remove any negative sign.
You have a minimumFoundSoFar variable initially set to a very big value. If the result of this subtraction is less than the minimumFoundSoFar variable you transfer the loop index into the result variable.
At the end of the loop the result variable has the index of the closest match.

Grumpy_Mike

Give a man a fish and he is fed for a day, teach him how to fish and he is fed for life.

PaulS

Quote
Give a man a fish and he is fed for a day, teach him how to fish and he is fed for life.

Or until the fish are all gone.

Go Up