Quick Index
Steps



Demo


Here is a demo (1 min 54 seconds)

Problem Statement


The function mapElements returns a new collection which is the passed collection mapped (converted) to new elements using the passed mapping function.

Write an algorithm (human language) and then write pseudocode.

Function header: function mapElements(elements, mapFct)

The passed mapFct is invoked with input that is an element (from the passed elements array) and outputs a new element.

Example Hand Calculation #1:

elements = [2, 3, 4];
mapFct = (x) => x * x;
mapElements(elements, mapFct) outputs [4, 9, 16]

Example Hand Calculation #2:

elements = ['Asha', 'Acheampong', 'Mo'];
mapFct = (str) => str.length;
mapElements(elements, mapFct) outputs [4, 10, 2]






































































































Hints


General Hints:



Specific Hints:







































































































Solution


Algorithm:

/**Returns new collection using mapFct to produce new elements */
function mapElements(elements, mapFct)
	Let newElements = new dynamic (growable) array
	Iterate over collection "elements" (let "nextElement" be the iteration variable)
		Let newElement = mapFct(nextElement)
		Add newElement to newElements
	Return newElements


Pseudocode:

/**Returns new collection using mapFct to produce new elements */
function mapElements(elements, mapFct) {
	let newElements = [];
	for (let nextElem of elements) {
		let newElem = mapFct(nextElem);
		newElements.add(newElem);
	}
	return newElements
}

//-------------------------------------------
//Tests
var elements, squareFct, lengthFct, result;

elements = [2, 3, 4];
squareFct = (x) => x * x;
println("Data: " + elements);
println("Squares: " + mapElements(elements, squareFct));

elements = ['Asha', 'Acheampong', 'Mo'];
lengthFct= (str) => str.length;
println("\nData: " + elements);
println("Lengths: " + mapElements(elements, lengthFct));