Quick Index
Steps



Problem Statement


Write a function named findLast that returns the index of the last match, or -1 if no match. by "last match" we mean the match closes to the end of the input array. Hint: start the search at the end and work backwards.

Function header: "function findLast(elements, matchFct)"

The passed matchFct is invoked with input that is an old element (from the passed elements array) and it outputs true if the given element is a match.

Example Hand Calculation #1:

elements = [10, 11, 12, 13, 14, 15];
//fct returns true if x is odd
matchFct = (x) => x % 2 == 1;
findLast(elements, matchFct) outputs 5
//index 5 is the index of the last match (odd number 15)


Example Hand Calculation #2:

elements = [10, 11, 12, 13, 14, 15];
//fct returns true if x is greater than 11
matchFct = (x) => x > 11;
findLast(elements, matchFct) outputs 5
//index 2 is the index of the last match (15 > 11)


Example Hand Calculation #3:

elements = [10, 11, 12, 13, 14, 15];
//fct returns true if x is greater than 100
matchFct = (x) => x > 100;
findLast(elements, matchFct) outputs -1
//no element is > 100, so the output is -1 indicating no match






































































































Hints







































































































Solution


Algorithm:

/**Returns index of last match using matchFct, or -1 if no match*/
function findLast(elements, matchFct)
	Iterate (in reverse) over all indexes in collection ("i")
		Let elem be element at index "i"
		If (matchFct(elem))
			Return i
	Return -1


Pseudocode:

/**Returns index of last match using matchFct, or -1 if no match*/
function findLast(elements, matchFct) {
	//We'll use var "i" to represent "nextIndex"
	for (let i = elements.size() - 1; i >= 0; i--) {
		let elem = elements.get(i);
		if (matchFct(elem))
			return i;
	}
	return -1;
}

//-------------------------------------------
//Tests
var elements, matchFct, index;
elements = [10, 11, 12, 13, 14, 15];
println('Data: ' + elements);

//fct returns true if x is odd
matchFct = (x) => x % 2 == 1;
index = findLast(elements, matchFct);
println('Last Index of Odd Number: ' + index);

//fct returns true if input x is even
matchFct = (x) => x % 2 == 0
index = findLast(elements, matchFct);
println('Last Index of Even Number: ' + index);

//fct returns true if x is greater than 100
matchFct = (x) => x > 100;
index = findLast(elements, matchFct);
println('Last Index of Number Greater Than One Hundred: ' + index);