Problem Statement:
Write an algorithm to find the first matching element in a collection named "elements". Use "compareFct" to determine if we have a match. Return the index of the match, or "-1" if no match.
Given:
Variable 'elements' that holds a collection of objects
Variable 'compareFct', when evaluated like this "compareFct(anElem)", returns true if "anElem" is a "match"
Sample 1:
If we have elements [5, 10, 0, 10, 8, 3]
And if we look for a match of "10" using our new algorithm "find"
Then the result (index) should be 1
Index 1 holds the first "10" in the collection (there are two "10" elements in this collection)
Sample 2:
If we have elements [5, 8, 0, 10, 8, 3]
And if we look for a match of "10" using our new algorithm "find"
Then the result (index) should be 3
Index 3 holds the first "10" in the collection (there is only one "10" in this collection)
Writing Algorithm in Human Language
Write the algorithm in human language (English).
Human Language:
find(elements, compareFct) {
Let 'i' equal to zero
Let 'len' equal to length of 'elements'
While 'i' is less than 'len'
Let 'nextElement' equal to the element in 'elements' at index 'i'
If (compareFct(nextElement))
Return i;
Let 'i' equal to 'i' plus 1
Return -1
}
Writing Algorithm in Pseudocode
Write the algorithm in pseudocode.
Pseudocode:
function find(elements, compareFct) {
let len = elements.length
let i = 0
while (i < len) {
let nextElem = elements[i]
if (compareFct(nextElem))
return i
i = i + 1
}
return -1
}
//Try It
let nums = [2, 10, 20, 30, 31, 40, 41]
//First num >= 20;
let matchFct = (nextNum) => nextNum >= 20;
let matchIndex = find(nums, matchFct);
println("Match (>=20): " + nums[matchIndex]);
//First odd num
matchFct = (nextNum) => nextNum % 2 != 0
matchIndex = find(nums, matchFct);
println("Match (first odd): " + nums[matchIndex]);
Data Structures And Algorithms (DSA)
(Chapter 102 - Introduction to Pseudocode)