in Code

Each week, I offer up a JavaScript code challenge. Want more? You can find others here.

This week’s code challenge again comes from Coderbyte. It’s quite a bit easier and shorter than last week mainly because I was slammed with Drink for Pink events and prepping for the Automattic Grand Meetup!

Here’s the gist:

Using the JavaScript language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number divided by the total amount of letters in the string. For example: if str is “Hello6 9World 2, Nic8e D7ay!” the output should be 2. First if you add up all the numbers, 6 + 9 + 2 + 8 + 7 you get 32. Then there are 17 letters in the string. 32 / 17 = 1.882, and the final answer should be rounded to the nearest whole number, so the answer is 2. Only single digit numbers separated by spaces will be used throughout the whole string (So this won’t ever be the case: hello44444 world). Each string will also have at least one letter.

Here’s a test case for example:

Input = “H3ello9-9”
Expected Output = 4

The string “H3ello9-9” contains 6 items that aren’t numbers. If you sum up the numbers (9,9,3), you’ll get 21. If you divide that by 6, you get 3.5, which rounds to 4.

Here’s another test case:

Input = “One Number1
Expected Output = 0

Here’s my solution collapsed:

function numberSearch(str) {
	var separatedString = str.split('');
	var letters = [];
	var numbers = [];
	var sum = 0;

	for (var i=0; i<str.length; i++) {
		var currentItem = separatedString[i];
		if (isNaN(parseInt(currentItem))) {
			letters.push(currentItem);
		} else {
			numbers.push(currentItem);
		};
	};

	for (var i=0; i<numbers.length; i++) {
		currentNumber = Number(numbers[i]);
		sum = sum + currentNumber;
	};

	return (Math.round(sum/letters.length));
};

First, we create some variables we’ll need later on. The first (separatedString) breaks up the given string. The variables letters and numbers hold empty arrays. Then, we set the sum to 0.

Next, we cycle over the string determining whether or not currentItem is a number by using isNaN(parseInt(currentItem)). If the item isn’t a number, push it on to the letters array. If it is a number, push it on to the numbers array.

Next, we cycle over the numbers array and add the currentNumber to the sum total.

Finally, we use the Math.round() method to round up the result of sum divided by letters.length and return that number.

Leave a Thought