Coderbyte
Number Search
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.

function NumberSearch(str) {
// Initialize variables for total sum and letter count
var total = 0;
var letterCount = 0;
// Loop through each character in the input string
for (var i = 0; i < str.length; i++) {
var char = str.charAt(i);
// If the character is a number, add it to the total
if (!isNaN(char) && char !== " ") { // Exclude spaces from the sum
total += parseInt(char);
}
// If the character is a letter, increment the letter count
if (/[a-zA-Z]/.test(char)) {
letterCount++;
}
}
// Calculate the average by dividing the total by the letter count
var avg = total / letterCount;
// Round the average to the nearest integer and return it
return Math.round(avg);
}
// keep this function call here
console.log(NumberSearch(readline()));
Leave a Reply