Quick Index
Steps



Problem Statement


Use the same problem statement used for the algorithm problem

Convert the psuedocode solution to Java.





































































































Hints







































































































Solution


Algorithm:

public class FunctionPassingDrill {
	/**Returns index of first match using matchFct, or -1 if no match*/
	public static <T> int findFirst(List<T> elements, Function<T, Boolean> matchFct) {
		for (int i = 0; i < elements.size(); i++) {
			T nextElem = elements.get(i);
			if (matchFct.apply(nextElem))
				return i;
		}
		return -1;
	}
}

//_test_
private void experiment() {
	println("\ntest_findFirst");
	List<Integer> nums = Arrays.asList(10, 11, 12, 13, 14, 15);
	int matchIndex;
	//input integer, output boolean
	Function<Integer, Boolean> isOddFct, isLargeFct;
	println("Data: " + nums);

	//fct returns true if input x is odd
	isOddFct = (x) -> x % 2 == 1;
	matchIndex = FunctionPassingDrill.findFirst(nums, isOddFct);
	println("Index of first odd number: " + matchIndex);

	//fct returns true if input x is greater than 11
	isLargeFct = (x) -> x > 11;
	matchIndex = FunctionPassingDrill.findFirst(nums, isLargeFct);
	println("Index of first number greater than 11: " + matchIndex);

	//fct returns true if input x is greater than 100
	isLargeFct = (x) -> x > 100;
	matchIndex = FunctionPassingDrill.findFirst(nums, isLargeFct);
	println("Index of first number greater than 100: " + matchIndex);
}