### re: Daily Coding Puzzles - Oct 29th - Nov 2nd VIEW POST

Solved it awhile ago (forgot about it).

``````using System.Linq;
using System;

public class Kata
{
public static int[] CountPositivesSumNegatives(int[] a)
{
// guard clause for edge cases
if (a == null || a.Length == 0) return new int[0];

int count = 0;
int sum = 0;
// ".ToList()" is required to iterate the sequence
a.Select(n => n > 0 ? count++ : sum += n).ToList();

return new[] {count, sum};
}
}
``````

And just re-solved it using JavaScript

``````function countPositivesSumNegatives(input) {
return (input && input.length >= 1)
? input.reduce((acc, n) => {
n > 0 ? acc[0]++ : acc[1] += n;
return acc;
}, [0, 0])
: [];
}
``````

The C# version is likely better solved with the linq aggregate monad. Less ram, no side effects.

Thanks for the suggestion there, @asparallel .

Here is the updated C# code (with the same logic as JavaScript one) using `.Aggregate`.

``````using System.Linq;
using System;

public class Kata
{
public static int[] CountPositivesSumNegatives(int[] a)
{
return (a == null || a.Length == 0)
? new int[0]
: a.Aggregate(new [] {0, 0}, (acc, n) => {
if (n > 0) acc[0]++;
else acc[1] += n;
return acc;
});
}
}
``````

Further optimization I'd probably press for, use a tuple to move the entire aggregation onto the stack:

``````  public static IList<int> CountPositivesSumNegatives(int[] values)
{
if (values == null || values.Length == 0) return new int[0];

var result = values.Aggregate((0, 0), (seed, value) =>
{
if (value > 0) seed.Item1++;
else seed.Item2 += value;
return seed;
});

return new[] { result.Item1, result.Item2 };
}
``````

Ah ha. Tuple being a value type, it is better optimized.
Thanks for the tips there 👊

code of conduct - report abuse