mercredi 9 avril 2014

Java - tableau exercice Confusion - Stack Overflow


I have written a (so far incomplete) method that should take an array of ints, find the difference between neighboring cells, and then return the smallest difference.


For example:


[9, 16, 4, 8, 20] --> 7, 12, 4, 12 --> 4


[12, 21, 33, 6, 3, 3] --> 9, 12, 27, 3, 0 --> 0


Here's my method:


public static int minGap(int[] a) {
int gap = 0;
for (int i = 0 ; i < (a.length - 1) ; i++) {
gap = Math.abs(a[i + 1] - a[i]);
System.out.println(gap);
}
return gap;
}

I believe that I have the intermediate step correct (finding the differences), but I cannot figure out how to then compare all them and produce the smallest one. I'm assuming I will use an if-statement, but I only have the one variable "gap" to work with.


Please let me know your suggestions.




Introduce a new variable for the smallest gap found so far. It can be initialized to something huge, probably Integer.MAX_VALUE.


In the loop, if the current gap is smaller than the smallest gap found so far, then set the smallest gap found so far to the current gap. Then after the for loop completes, you have the smallest gap.




Just add a min variable and update it as needed.


public static int minGap(int[] a) {
int gap = 0;
int min = 0;
for (int i = 0 ; i < (a.length - 1) ; i++) {
gap = Math.abs(a[i + 1] - a[i]);
if (i==0 || gap < min) min = gap;
System.out.println(gap);
}
return min;
}


I have written a (so far incomplete) method that should take an array of ints, find the difference between neighboring cells, and then return the smallest difference.


For example:


[9, 16, 4, 8, 20] --> 7, 12, 4, 12 --> 4


[12, 21, 33, 6, 3, 3] --> 9, 12, 27, 3, 0 --> 0


Here's my method:


public static int minGap(int[] a) {
int gap = 0;
for (int i = 0 ; i < (a.length - 1) ; i++) {
gap = Math.abs(a[i + 1] - a[i]);
System.out.println(gap);
}
return gap;
}

I believe that I have the intermediate step correct (finding the differences), but I cannot figure out how to then compare all them and produce the smallest one. I'm assuming I will use an if-statement, but I only have the one variable "gap" to work with.


Please let me know your suggestions.



Introduce a new variable for the smallest gap found so far. It can be initialized to something huge, probably Integer.MAX_VALUE.


In the loop, if the current gap is smaller than the smallest gap found so far, then set the smallest gap found so far to the current gap. Then after the for loop completes, you have the smallest gap.



Just add a min variable and update it as needed.


public static int minGap(int[] a) {
int gap = 0;
int min = 0;
for (int i = 0 ; i < (a.length - 1) ; i++) {
gap = Math.abs(a[i + 1] - a[i]);
if (i==0 || gap < min) min = gap;
System.out.println(gap);
}
return min;
}

0 commentaires:

Enregistrer un commentaire