Answer to Question #82321 in C# for vikas

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
1
Expert's answer
2018-10-24T13:49:09-0400

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.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS