Java - distanceBetweenMinAndMax returns difference between the minPosition and t
ID: 3686057 • Letter: J
Question
Java - distanceBetweenMinAndMax returns difference between the minPosition and the maxPosition in an array of doubles. You can assume the array is nonempty and has no duplicates. Your solution must go through the array exactly once. Your solution must not call any other functions. Here are some examples (using "==" informally):
<pre>
0 == distanceBetweenMinAndMax(new double[] { -7 }) // -7,-7 are the min and max
3 == distanceBetweenMinAndMax(new double[] { 1, -4, -7, 7, 8, 11 }), // -7,11
5 == distanceBetweenMinAndMax(new double[] { -13, -4, -7, 7, 8, 11 }) // -13,11
1 == distanceBetweenMinAndMax(new double[] { 1, -4, -7, 7, 8, 11, -9 }) // -9,11
</pre>
public static int distanceBetweenMinAndMax (double[] list) {
return 0; // TODO
}
Explanation / Answer
public static int distanceBetweenMinAndMax(double[] list){
double min=list[0];
double max=list[0];
int min_ind,max_ind;
for(int index=0;list[index]!=NULL;index++)
{
if(min>list[index]){
min=list[index];
min_ind=index;}
if(max<list[index])
{
max=list[index];
max_ind=index;
}
}
if(min_ind>max_ind)
return min_ind-max_ind;
else
return max_ind-min_ind;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.