Quick Index
Steps



Demo


Here is a demo (1 min 18 seconds)

Problem Statement


Write a function named findFirst that returns the index of the first match, or -1 if no match.

Function header: "function findFirst(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;
findFirst(elements, matchFct) outputs 1
//index 1 is the index of the first match (odd number 11)


Example Hand Calculation #2:

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)


Example Hand Calculation #3:

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






































































































Hints







































































































Solution


Algorithm:


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


Pseudocode:

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