Intro

So this problem came in the Computer-Science Introduction Exam. It gives you an array of values equal to either F(emale) or M(ale). You need to return amount of occurances of F and M.

Originally the Exam wanted the examinee to implement this in flowchart, but i’ll implement in javascript instead.

Value Type

The array could be integer, bool or string. But for simplicity’s sake, we’ll use strings of one character length so either M or F.

Code

First, start out with a simple loop.

for(var i in arr) {
	var v = arr[i];
}

Then, compare the value to F or M.

for(var i in arr) {
	var v = arr[i];
	if(v == "F") {
	} else if (v == "M") {
	}
}

Oh shoot, we forget to add the variables.

var F = 0;
var M = 0;
for(var i in arr) {
	var v = arr[i];
	if(v == "F") {
	} else if (v == "M") {
	}
}

Oh yeah, increment the variables.

var F = 0;
var M = 0;
for(var i in arr) {
	var v = arr[i];
	if(v == "F") {
		F++
	} else if (v == "M") {
		M++;
	}
}

Finally, wrap it in a nice beautiful function.

function solve(arr) {
	var F = 0;
	var M = 0;
	for(var i in arr) {
		var v = arr[i];
		if(v == "F") {
			F++
		} else if (v == "M") {
			M++;
		}
	}
	
	return {F: F, M: M};
}
// solve(["F", "M", "M", "M", "F", "F", "F", "F", "M", "F"])
// should output: {F: 6, M: 4}

Google Chrome Console Output


Bonus

Automate this function to calculate unspecified occurances of string in the array. Return the occurances in an Object.

function solve(arr) {
	var obj = {};
	
	for(var i in arr) {
		var v = arr[i];
		if(obj[v] === undefined) {
			obj[v] = 0 ;
		}
		
		obj[v]++;
	}
	
	return obj
}
// solve(["U", "M", "M", "M", "F", "F", "F", "F", "M", "U"])
// should output: {U: 2, M: 4, F: 4}