Go Down

Topic: Compare value to array (Read 670 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.

AWOL

Teach a man to fish and he will sit by a lake drinking beer all day
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

jraskell


Teach a man to fish and he will sit by a lake drinking beer all day


According to the proverb, only if somebody has given him or taught him how to make the beer.

Khalid

Thanks Sui..at-least i learn something today... One Fish in Hand is better than two fishes in Pond ]:D
Simply...You can't afford me..

Author Of:
http://my-woodcarving.blogspot.com/
http://www.free3dscans.blogspot.com/
http://my-diysolarwind.blogspot.com/

Oops..some one gave me Karma...:)

Go Up