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

VIEW PARENT COMMENT VIEW FULL DISCUSSION

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