DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #185 - House Numbers Sum

Setup

A boy is walking home from school. To make the walk more enjoyable, he decides to add up the numbers of the houses he passes during his walk. Unfortunately, the numbers won't appear to him in any specific order, since he's regularly taking turns.

At some point during the walk, the boy encounters a house marked number 0. This surprises him so much that he stops adding the numbers after that house to the total.

For the given array of house numbers, determine the sum that the boy will get. There will always be at least one number 0 house on the path.

Examples

inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2] => 11

inputArray = [1, 4, 34, 124, 2, 0, 14, 51] => 165

Tests

inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]

inputArray = [4, 2, 1, 6, 0]

inputArray = [4, 1, 2, 3, 0, 10, 2]

Good luck!


This challenge comes from myjinxin2015 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (8)

Collapse
 
cipharius profile image
Valts Liepiņš

My original solution in Ruby

def houseNumSum arr
    arr.reduce(0) do |result,x|
        return result if x == 0
        result += x
    end
end

and after being inspired by Craig's solution:

def houseNumSum arr
    arr.take_while {|x| x != 0}.sum
end
Collapse
 
craigmc08 profile image
Craig McIlwrath

Simple Haskell solution

houseSum :: (Eq a, Num a) => [a] -> a
houseSum = sum . takeWhile (/=0)
Collapse
 
madza profile image
Madza
const sum = arr.slice(0, arr.indexOf(0)).reduce((a, b) => a + b, 0);
Collapse
 
savagepixie profile image
SavagePixie

Elixir

defmodule Challenge do
  def housenumsum([ 0 | _tail ]), do: 0
  def housenumsum([ head | tail ]), do: head + housenumsum(tail)
end
Collapse
 
vidit1999 profile image
Vidit Sarkar

C++ solution

int sumHouse(vector<int> numbers){
    int sum = 0;
    for(int i: numbers){
        if(i==0)
            return sum;
        sum += i;
    }
}
Collapse
 
hnicolas profile image
Nicolas Hervé

Javascript

const sum = (arr) => arr.slice(0, arr.indexOf(0)).reduce((acc, curr) => acc + curr, 0);
Collapse
 
testingpro profile image
testingpro • Edited

JavaScript


const sum = inputArray =>
inputArray.slice(0, inputArray.indexOf(0)).reduce((a, b) => a+b);
sum(inputArray);
Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

If a test case doesn't have an expected output, is it really a test case?

Also, what did the boy do for houses with numbers like "14A" or houses that have names, and no number?