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)
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)
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
/**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
/**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);