Some error occured while loading page for you. Please try again.
Sort 52 Discussions, By:
Please Login in order to post a comment
f arr = sum (filter odd arr)
-- OR --
f = sum . filter odd
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
Same in Erlang, I used
case abs(N rem 2) of
1 -> true;
0 -> false
def f(arr:List[Int]) = arr filter(_ % 2 != 0) reduceLeft(_ + _)
Nice way to dodge a bullet with negative numbers!
I fell for that trap
arr.filter(_ % 2 != 0).sum
any reason for reduceLeft over sum?
Fun with Haskell.
f arr = sum [ x | x <- arr, odd x ]
why i received "wrong answer" for test:
25+(-1)+(-2)+23+(-8) = 19, but in test case answer is 39
The problem is not to sum the elements at odd index but the elements which are odd.
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]))
Thanks for pointing. I have updated the sample case to avoid this.
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
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.
Haskell recursive :)
f (h:t) = x*h + f t where x=mod h 2
f _ = 0
f arr = sum (filter (odd) arr)
You can use just : f = sum . filter odd
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
Haskell with list comprehensions
f xs = sum $ [ x | x <- xs, x `mod` 2 >0]