Theme: Logic first, syntax later.

Video for this page...

Starting Point
We are given that we are in a MyArray and the algorithm receives one arg "searchFct"
occurrences(matchFct)
	//Object "this" is a MyArray
	/*Return a count (number) of the number of occurrences where
	matchFct returns true over our elements.*/
}
Logic Pass 1
  • Initialize the result (count = 0).
  • Iterate over all elements
  • In each loop, run the function and inc count
occurrences(matchFct) {
	let count be 0
	iterate over elements (nextElem)
		match = matchFct(nextElem)
		Increment count
}
Logic Pass 1 - Test
let MyArray with elements [10, 20, 10]
let matchFct = anElem => anElem > 15
result = 3
Check: FAILS -- result should be 1
occurrences(matchFct) {
	let count be 0
	iterate over elements (nextElem)
		match = matchFct(nextElem)
		Increment count
}
Logic Pass 2
This time only increment count if match is true
occurrences(matchFct) {
	let count be 0
	iterate over elements (nextElem)
		match = matchFct(nextElem)
		if (match is true)
			Increment count
}
Logic Pass 2 - Test
let MyArray with elements [10, 20, 10]
let matchFct = anElem => anElem > 15
result = 1
Okay
occurrences(matchFct) {
	let count be 0
	iterate over elements (nextElem)
		match = matchFct(nextElem)
		if (match is true)
			Increment count
}
Pseudocode - Open Context Menu(s)
We now pull open MyArray's menu of available algorithms for use.

We select a couple (old buddies) that are helpful for iteration.
Context:
Pseudocode - Writing
We convert our logical ideas to more of a pseudocode feel.
// occurrences(matchFct)
var nextIndex, count
nextIndex = 0
count = 0
while (nextIndex < this.size()) {
	var nextElem, match
	nextElem = this.get(nextIndex)
	match = matchFct(nextElem)
	if (match)
		count++
	nextIndex++
}
return count;