In: Computer Science
In Java Please:
* posOfLargestElementLtOeT returns the position of the largest element in the array that is
* less than or equal to the limit parameter
* if all values are greater than theVal, return -1;
*
* Precondition: the array is nonempty and all elements are unique.
* Your solution must go through the array exactly once.
*
* <pre>
* 0 == posOfLargestElementLtOeT(3, new double[] { -7 }) // value:-7 is in pos 0
* 5 == posOfLargestElementLtOeT(3, new double[] { 11, -4, -7, 7, 8, 1 }), // value:1 is in pos 5
* -1 == posOfLargestElementLtOeT(-7, new double[] { 1, -4, -5, 7, 8, 11 }), // all elements are > -7
*
* The code below is a stub version, you should replace the line of code
* labeled TODO with code that achieves the above specification
* </pre>
*/
public static int posOfLargestElementLtOeT( double limit, double[] list)
// Solve here
public class PosLargest {
/**
* posOfLargestElementLtOeT returns the position of the largest element in the array that is
* <p>
* less than or equal to the limit parameter
* <p>
* if all values are greater than theVal, return -1;
* <p>
* <p>
* <p>
* Precondition: the array is nonempty and all elements are unique.
* <p>
* Your solution must go through the array exactly once.
*
*
*
* <pre>
*
* 0 == posOfLargestElementLtOeT(3, new double[] { -7 }) // value:-7 is in pos 0
*
* 5 == posOfLargestElementLtOeT(3, new double[] { 11, -4, -7, 7, 8, 1 }), // value:1 is in pos 5
*
* -1 == posOfLargestElementLtOeT(-7, new double[] { 1, -4, -5, 7, 8, 11 }), // all elements are > -7
*
*
*
* The code below is a stub version, you should replace the line of code
*
* labeled TODO with code that achieves the above specification
*
* </pre>
*/
public static int posOfLargestElementLtOeT(double limit, double[] list) {
int maxIndex = -1;
for (int i = 0; i < list.length; i++) {
if (list[i] <= limit) {
if (maxIndex == -1 || list[i] > list[maxIndex]) {
maxIndex = i;
}
}
}
return maxIndex;
}
public static void main(String[] args) {
System.out.println(posOfLargestElementLtOeT(3, new double[]{-7}));
System.out.println(posOfLargestElementLtOeT(3, new double[]{11, -4, -7, 7, 8, 1}));
System.out.println(posOfLargestElementLtOeT(-7, new double[]{1, -4, -5, 7, 8, 11}));
}
}
