How to find Minimum Distance between two Numbers ?



How to find Minimum Distance between two Numbers ?

  • Using two loops to find the minimum distance between two numbers,
    • All the elements of arr[] one by one picks by outer loop.
    • The inner loop picks all the elements after the element picked by outer loop.
    • If the elements picked by outer and inner loops have same values as x or y then if needed update the minimum distance calculated so far.

Sample Code in C

#include <stdio.h> 
#include <stdlib.h> // for abs() 
#include <limits.h> // for INT_MAX 
  
int minDist(int arr[], int n, int a, int b) 
{ 
    int i, j; 
   int min_dist = INT_MAX; 
   for (i = 0; i < n; i++) 
   { 
     for (j = i+1; j < n; j++) 
     { 
         if( (a == arr[i] && b == arr[j] || 
              b == arr[i] && a == arr[j]) && min_dist > abs(i-j)) 
         { 
              min_dist = abs(i-j); 
         } 
     } 
   } 
   return min_dist; 
} 
  
/* Driver program to test above fnction */
int main()  
{ 
  int arr[] = {5, 7, 7, 2, 8, 9, 11, 11, 7, 5, 12, 6}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    int a = 7; 
    int b = 11; 
  
    printf("Minimum distance between %d and %d is %d\n", a, b,  
              minDist(arr, n, a, b)); 
    return 0; 
}

Output

Minimum distance between 7 and 11 is 1


Related Searches to How to find Minimum Distance between two Numbers ?