Given an unsorted dynamic array (arr) and two numbers x and y, find the minimum distance between x and y in the array (arr) using functions. The array might also contain duplicates. You may assume that both x and y are different and present in the array (arr). You are also advised to NOT use the INT_MAX and abs() function.
Sample Input & Output
Input: arr[ ] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, x = 3, y = 6
Output: Minimum distance between 3 and 6 is 4
(3 to 5 => 1 unit, 5 to 4 => 1 unit, 4 to 2 => 1unit & 2 to 6 => 1 unit
So, Total Minimum Distance = 1+1+1+1 = 4)
#include <stdio.h>
int MinDist(int arr[], int n, int x, int y);
int main() {
int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int x=3, y=6;
int m = MinDist(arr, n, x, y);
printf("Total minimum distance between %d and %d is %d\n", x, y, m);
return 0;
}
int MinDist(int arr[], int n, int x, int y) {
int i, i0, j;
int m=n+1;
for (i=0; i<n-1; i++) {
if (arr[i] == x) {
for (j=i+1; j<n; j++) {
if (arr[j] == x) {
i = j;
}
else if (arr[j] == y) {
if (j-i < m) {
m = j-i;
}
}
}
}
}
return m;
}
Comments
Thanks a lot !!
Leave a comment