## Sum of Odd Elements

balintant + 0 comments Haskell

f arr = sum (filter odd arr) -- OR -- f = sum . filter odd

- RD
Dionakov + 3 comments Scala:

def f(arr:List[Int]) = arr filter(_ % 2 != 0) reduceLeft(_ + _)

luizpericolo + 0 comments Nice way to dodge a bullet with negative numbers! I fell for that trap

xavier_guihot + 0 comments arr.filter(_ % 2 != 0).sum

- MR
deliam_arlen + 0 comments any reason for reduceLeft over sum?

arr.filterNot(_%2==0).sum

hpedrorodrigues + 0 comments Fun with Haskell.

f arr = sum [ x | x <- arr, odd x ]

- A
Parabellum + 1 comment why i received "wrong answer" for test: 11,25,18,-1,26,-20,-19,23,-24,-8 25+(-1)+(-2)+23+(-8) = 19, but in test case answer is 39

ingineer + 1 comment The problem is not to sum the elements at odd index but the elements which are odd.

mdgart + 1 comment It's confusing because in the example input both odd numbers and numbers with odd indexs produce the same results: 16

(apply + (take-nth 2 (rest [2 3 4 6 5 7 8 0 1])))

(apply + (filter (fn [x] (not= (mod x 2) 0)) [2 3 4 6 5 7 8 0 1]))

abhiranjan + 0 comments Thanks for pointing. I have updated the sample case to avoid this.

shiva_shinde + 1 comment Strange that is it not working, I am getting the output as 15, but the answer is 16.

Based on the input the answer should be 15, So, I don't know whats wrong with my code. This is in scala!!

def f(arr:List[Int]):Int = arr.zipWithIndex.filter(_._2%2 == 1).map(_._1).sum

- M
mattkrae + 0 comments It's the sum of the odd values not the values at the odd indices. I didn't read carefully either, had the same issue.

- OD
okaydemir + 0 comments Haskell recursive :)

f (h:t) = x*h + f t where x=mod h 2 f _ = 0

gmrodgers + 1 comment f arr = sum (filter (odd) arr)

AbhishekVermaIIT + 0 comments You can use just :

*f = sum . filter odd*

- O
Omnikron13 + 0 comments We're good to use in-built stuff like filter for this one, right? After the previous ones I wasn't so sure, so I solved it both ways, but it might be cool to make it clearer. =d

- H
hgsipiere + 0 comments Haskell with list comprehensions

f xs = sum $ [ x | x <- xs, x `mod` 2 >0]

Sort 52 Discussions, By:

Please Login in order to post a comment