Problem Given a numeric array A and a numeric value n, find the linear index AND the value of A’s…
Problem Given a numeric array A and a numeric value n, find the linear index AND the value of A’s element whose distance from n is nearest among all the elements (recall that we can linearly index a 2D array just like a 1D column array). A distance between two numbers, say x and y, are measured as the absolute difference between the two X – y. Note that the qualifying element may not be unique. In such a case, we want to return the index of the first occuring nearest element, that is, the smallest index among the nearest elements. Hint If you coded if-statement correctly, then you don’t really need to worry about this at all. Examples Consider the 3×3 array [11, 13, 18; 65, 25, 31; 49. 65. 37). • n = 60: The second element (65) is the nearest from n with the distance of 160 – 65| = 5. The 6th element (65) is also the nearest but it’s not the first occuring. • n = 25. The fifth element (25) is the nearest from n with the distance of 25 – 25] = 0. . n = 12: The first element (11) is the nearest from n with the distance of 12 – 111 = 1. The fourth element (13) is also the nearest from n (12 – 131 = 1) but it’s not the first occuring. Task Write a function nearestElement that takes two input arguments (in this order: an array to be searched and the search key) and returns two output values in this order an index of the first occurring nearest element of the input array and its value) Use of the built-in function “min” or other similar built-in functions will result in not passing the automatic assessment. Hints . Don’t be fooled by the example 2D array. This problem does not need a nested loop as long as you treat the 2D array like a 10 array with linear indexing. For example, given a 2D array M, what does M give you? – Take time to understand the problem and analyze it. If you take the element-wise difference between A and n, the resulting array should only consists of distances. What would you call the elements of the distance array that corresponds to the nearest elements in A? . Remember, “The server timed out while running… most likely means that you have an infinite loop in your code.