Question #82321

a function return the minimum distance between indices of an array that have adjacent values,the function should return -1 if the minimum distance is greater then 100,000,000. the function should return -2 if no adjacentindices exist

Expert's answer

static int MinDistance(int[] a, int idx)

{

if (idx < 0 || idx >= a.Length)

throw new Exception("The index is outside the array");

int d = -2;

for (int i = 0; i < a.Length; i++)

if ((a[i] == (a[idx] + 1) || a[i] == (a[idx] - 1)) && i != idx)

d = Math.Abs(idx - i);

if (d > 100000000)

return -1;

return d;

}

Function argument:

int[] a - the array in which we look for the distance;

int idx - index of the element for which we are looking for adjacent values.

## Comments

## Leave a comment