Sort 72 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
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.
r = ((a % b) + b) % b
This is very nice explanation on the reminder behavior. Thanks for sharing.
def f(arr:List[Int]) = arr filter(_ % 2 != 0) reduceLeft(_ + _)
Nice way to dodge a bullet with negative numbers!
I fell for that trap
me too :(
arr.filter(_ % 2 != 0).sum
any reason for reduceLeft over sum?
(fn [lst] (reduce + (filter odd? lst)))
(defun sum-odd (lst)
(apply '+ (remove-if-not #'oddp lst)))
My Elixir solution
|> Enum.reduce(fn (x, y) -> if rem(x,2)!=0, do: x+y, else: y end)
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