# Sum of Odd Elements

# Sum of Odd Elements

balintant + 0 comments Haskell

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

jsonsong + 2 comments it is strange thar -3 % 2 ==-1 in scala

so my first code :"arr.filter(_%2==1).sum" is faild when negative number in the input .

fix it by _%2!=0

choroba + 0 comments Same in Erlang, I used

case abs(N rem 2) of 1 -> true; 0 -> false end.

eveningsteps + 1 comment There's nothing strange (and this goes for every language), as the definition of Euclidean division requires remainder to be within

`[0, |b|)`

range. For the remainder to be positive, use`r = ((a % b) + b) % b`

formula.m_venkatbeece + 0 comments This is very nice explanation on the reminder behavior. Thanks for sharing.

Dionakov + 3 comments Scala:

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

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

m_venkatbeece + 0 comments me too :(

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

deliam_arlen + 0 comments any reason for reduceLeft over sum?

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

denisdifazio + 0 comments Clojure

(fn [lst] (reduce + (filter odd? lst)))

jinrou + 0 comments common lisp:

(defun sum-odd (lst) (apply '+ (remove-if-not #'oddp lst)))

adrielradicchi + 0 comments My Elixir solution

IO.read(:stdio, :all) |> String.split |> Enum.map(&String.to_integer(&1)) |> Enum.reduce(fn (x, y) -> if rem(x,2)!=0, do: x+y, else: y end) |> IO.puts

hpedrorodrigues + 0 comments Fun with Haskell.

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

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

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.

okaydemir + 0 comments Haskell recursive :)

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

Sort 72 Discussions, By:

Please Login in order to post a comment