Problem Statement:
Write an algorithm that takes two parameters (a collection of elements, and a collection of match functions. Each match function returns the matching index of the match in the elements. Return the sum of the matching indexes.
Given:
Variable 'elements' that holds a collection of objects
Variable 'matchFcts', that is a collection of match functions -- each match function returns the matching index of the match in the elements
Reuse:
We are able to reuse algorithms from other problems -- hint: find(elements, compareFct)
Special Case:
If any matchFunction does not find a mach (i.e., returns -1) then this algorithm returns -1
Sample 1:
If we have elements [5, 8, 0, 10, 8, 3]
Assume the match functions match 5 and 3.
The matching indexes in "elements" are 0 and 5
The sum is 0 + 5 = 5
Sample 2:
If we have elements [5, 10, 0, 10, 8, 3]
Assume the match functions match 10, 5, 8 and 3.
The matching indexes in "elements" are 1, 0, 4 and 5.
The sum is 1 + 0 + 4 + 5 = 10
Writing Algorithm in Human Language
Write the algorithm in human language (English).
Human Language:
computeSumOfMatchingIndexes(elements, matchFunctions) {
Let sum be set to 0
Set i to zero
Set len to length of 'matchFunctions'
While i is less than len
Let nextMatchFct equal to the matchFct in matchFunctions at index i
Let nextMatchIndex = find(elements, nextMatchIndex)
//Special case
If nextMatchIndex < 0
Return -1
Let sum be set to sum + nextMatchIndex
Let i equal to i plus 1
Return sum
}
Writing Algorithm in Pseudocode
Write the algorithm in pseudocode.
Pseudocode:
function computeSumOfMatchingIndexes(elements, matchFunctions) {
var sum, i, len
sum = 0
i = 0
len = matchFunctions.length
while (i < len) {
var nextMatchFct, nextMatchIndex
nextMatchFct = matchFunctions[i]
nextMatchIndex = find(elements, nextMatchFct)
//Special case
if (nextMatchIndex < 0)
return -1
sum += nextMatchIndex
i++;
}
return sum
}
//Try It
let nums, matcher1, matcher2, matchers, sum;
nums = [5, 8, 0, 10, 8, 3];
matcher1 = (next) => next == 5;
matcher2 = (next) => next == 3;
matchers = [matcher1, matcher2]
//We should find indexes 0 and 5, sum is 5
println("Expecting sum: 5");
sum = computeSumOfMatchingIndexes(nums, matchers);
println("Actual sum: " + sum);
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
}
Data Structures And Algorithms (DSA)
(Chapter 102 - Introduction to Pseudocode)