elements = [10, 11, 12, 13, 14, 15]; //fct returns true if x is odd matchFct = (x) => x % 2 == 1; findFirst(elements, matchFct) outputs 1 //index 1 is the index of the first match (odd number 11)
elements = [10, 11, 12, 13, 14, 15]; //fct returns true if x is greater than 11 matchFct = (x) => x > 11; findFirst(elements, matchFct) outputs 2 //index 2 is the index of the first match (12 > 11)
elements = [10, 11, 12, 13, 14, 15]; //fct returns true if x is greater than 100 matchFct = (x) => x > 100; findFirst(elements, matchFct) outputs -1 //no element is > 100, so the output is -1 indicating no match
/**Returns index of first match using matchFct, or -1 if no match*/ function findFirst(elements, matchFct) Iterate over all indexes in collection (loop variable is named "nextIndex") Let nextElem be element at index "nextIndex" If (matchFct(nextElem)) Return nextIndex Return -1
/**Returns index of first match using matchFct, or -1 if no match*/ function findFirst(elements, matchFct) { //We'll use var "i" to represent "nextIndex" for (let i = 0; i < elements.size(); i++) { let nextElem = elements.get(i); if (matchFct(nextElem)) 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 = findFirst(elements, matchFct); println('First Index of Odd Number: ' + index); //fct returns true if x is greater than 11 matchFct = (x) => x > 11; index = findFirst(elements, matchFct); println('First Index of Number greater than eleven: ' + index); //fct returns true if x is greater than 100 matchFct = (x) => x > 100; index = findFirst(elements, matchFct); println('First Index of Number greater than one hundred: ' + index);