Find number from given list for which value of the function is closest to A in C++


Suppose we have a function F(n) such that F(n) = P – (0.006*n), where P is also given. Given a list of integers and a number A. The task is to find the number from given list, for which the value of the function is nearer to A. So if P = 12, and A = 5, then list will be {1000, 2000} So output will be 1000. So if P = 12 and A = 5, then for 1000, F(1000) = 12 – (0.006 * 1000) = 6 and for 2000, F(2000) = 12 – (0.006 * 2000) = 0, as the nearest value to 5 is the 6, so that is taken.

Iterate through each value in the list, and find F(n) for every value. Now compare the absolute difference of every value of F(n) and A and the value of n, for which the absolute difference is minimum, will be the answer.

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int nearestValue(int P, int A, int N, int arr[]) {
   int ans = -1;
   float temp = (float)INFINITY;
   for (int i = 0; i < N; i++) {
      float term = P - arr[i] * 0.006;
      if (abs(term-A) < temp) {
         temp = abs(term - A);
         ans = i;
      }
   }  
   return arr[ans];
}
int main() {
   int P = 12, A = 5;
   int array[] = {1000, 2000, 1001};
   int N = sizeof(array)/sizeof(array[0]);
   cout << "Nearest value is: " << nearestValue(P, A, N, array) << endl;
}

Output

Nearest value is: 1001

Updated on: 18-Dec-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements