Interview Questions

Oddball sum

The practice coding question created by App Academy:
## Sources

http://prepwork.appacademy.io/coding-test-1/practice-coding-exercise/
## Code

Write a function called oddball_sum which takes in a list of numbers and returns the sum of all the odd elements.

To solve this challenge we'll simply loop through the array while maintaining a final count, and every time an odd number is encountered we'll add it to the count.
function oddball_sum(nums) { // final count of all odd numbers added up var final_count = 0; // loop through entire list for (var i = 0; i < nums.length; i++) { // we divide by 2, and if there is a remainder then // the number must be odd so we add it to final_count if (nums[i] % 2 === 1) { final_count += nums[i] } } return final_count; } oddball_sum([1, 2, 3, 4, 5]);

def oddball_sum(nums): # final count of all odd numbers added up final_count = 0 # loop through entire list for i in xrange(0, len(nums)): # we divide by 2, and if there is a remainder then # the number must be odd so we add it to final_count if nums[i] % 2 == 1: final_count += nums[i] return final_count print oddball_sum([1, 2, 3, 4, 5])

mrdaniel
published this on 1/31/16 **|**

4

@thedragon That's actually more abstract, which makes it more dificult for someone learning JavaScript to grasp the concepts of iteration. In your example you're introducing: built-in methods, higher-order functions/callbacks, scoping, and the introduction of a call stack (via reduce). So, no. That's not simpler for a beginner. It's probably the route I'd take in solving the problem, but it's not how I'd teach a beginner about iteration and conditional checking. Also, it's not any faster as both solutions run in a linear time complexity.

richardjboothe

commented on 10/01/16

1

I agree with @richardjboothe.
@thedragon - your code doesn't seem to take into account if the first element in the array is not an odd number. Will work with [1, 2, 3, 4, 5], but not with [2, 3, 4, 5].

esmaDev

commented on 03/18/17

1

Why don't you use reduce? Isn't this simpler?

function oddball_sum(nums) { return nums.reduce(function(total, item){ if (item % 2 === 1) { return total += item; } return total; }); }

thedragon

commented on 07/16/16

Log in to submit a comment.