Given a matrix, finding the closest zero to a chosen reference point requires us to do the following:
Find the distances of all zeros from the reference point.
Select the point with the least distance.
The cell marked X is the chosen reference point and the cell colored orange is the nearest zero.
In the case above, the minimum distance is 2.236.
A brute-force solution is relatively simple as shown in the code below:
#import relevant librariesimport numpy as np#randomly select reference pointi = np.random.randint(15)j = np.random.randint(15)print('Reference point [i,j]: [', i, ',',j, ']')# randomly generate 15x15 matrixarr = np.random.randint(10, size=(15, 15))# find indexes of all zeroszeros = np.argwhere(arr == 0)#print('zeros: \n', zeros)# find distances of all zeros from reference pointdist = np.sum((zeros-[i,j])**2, axis=1)#print("distances, \n", dist)# select point with minimum distanceindex = np.argmin(dist)# print the point and its distanceprint('min_distance: ', np.sqrt(dist[index]), 'at ', zeros[index])
Line 2: We import relevant libraries.
Line 5–7: We randomly select a reference point and print its coordinates.
Line 10: We randomly generate a 15x15 matrix.
Line 13: We find indexes of all zeros.
Line 17: We find the distances of all zeros from the reference point.
Line 21: We select the point with minimum distance.
Line 24: We print the point and its distance.
Free Resources