#include <iostream>
#include <cstdlib>
#include <ctime>
int dist( int a, int b)
{
return std:: abs ( b- a) ;
}
unsigned getClosest( int * nums, unsigned nNums, int target )
{
unsigned indexOfClosest = 0 ;
unsigned index = 1 ;
while ( index < nNums )
{
if ( dist( nums[ index] , target) < dist( nums[ indexOfClosest] , target) )
indexOfClosest = index ;
++ index ;
}
return indexOfClosest ;
}
void displayClosest( int * nums, unsigned nNums, int target)
{
std:: cout << "{ " ;
for ( unsigned i= 0 ; i< nNums; ++ i )
std:: cout << nums[ i] << ' ' ;
std:: cout << "}\n " ;
unsigned index = getClosest( nums, nNums, target) ;
std:: cout << "The closest number to " << target << " is " ;
std:: cout << nums[ index] << " at index " << index << ".\n " ;
}
int main( )
{
std:: srand ( std:: time ( 0 ) ) ;
const unsigned array_size = 3 ;
int array[ array_size] = { std:: rand ( ) % 20 , std:: rand ( ) % 20 , std:: rand ( ) % 20 } ;
for ( unsigned i= 1 ; i< 21 ; i+ = 2 )
displayClosest( array, array_size, i) ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0ZGxpYj4KI2luY2x1ZGUgPGN0aW1lPgoKaW50IGRpc3QoaW50IGEsIGludCBiKQp7CiAgICByZXR1cm4gc3RkOjphYnMoYi1hKSA7Cn0KCnVuc2lnbmVkIGdldENsb3Nlc3QoIGludCogbnVtcywgdW5zaWduZWQgbk51bXMsIGludCB0YXJnZXQgKQp7CiAgICB1bnNpZ25lZCBpbmRleE9mQ2xvc2VzdCA9IDAgOwoKICAgIHVuc2lnbmVkIGluZGV4ID0gMSA7CiAgICB3aGlsZSAoIGluZGV4IDwgbk51bXMgKQogICAgewogICAgICAgIGlmICggZGlzdChudW1zW2luZGV4XSwgdGFyZ2V0KSA8IGRpc3QobnVtc1tpbmRleE9mQ2xvc2VzdF0sIHRhcmdldCkgKQogICAgICAgICAgICBpbmRleE9mQ2xvc2VzdCA9IGluZGV4IDsKCiAgICAgICAgKytpbmRleCA7CiAgICB9CgogICA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