DEV Community

James Robb
James Robb

Posted on • Updated on

Sum of two lowest positive integers

Task description

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

Task solution

Tests

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Kata;

namespace KataTests.UnitTests 
{
    [TestClass]
    public class LowestNumbersTests
    {
        [TestMethod]
        public void TaskExamplesPassAsExpected()
        {
            var computer = new LowestNumbers();
            var numbers = new int[]{-1, 2, 3, 5};
            Assert.AreEqual(5, computer.sumSmallestNumbers(numbers));   
            Assert.AreEqual(10, computer.sumSmallestNumbers(numbers, 4));   
            Assert.Throws<ArgumentException>(() => computer.sumSmallestNumbers(numbers, 5));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

We take an array of integers into a function named sumSmallestNumbers and there is an optional parameter of how many to count. We also check that if too many are asked to be counted, an exception is raised.

Implementation

using System;
using System.Linq;

namespace Kata {
  public class LowestNumbers
  {
    public int sumSmallestNumbers(int[] numbers, int requiredCount = 2) {
      if(numbers.Length < requiredCount) {
        throw new ArgumentException(String.Format("{0} only contains {1} items but {2} were requested.", numbers, numbers.Length, requiredCount));
      }

      Array.Sort(numbers);
      return numbers.Where(i => i >= 0).Take(requiredCount).Sum();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This is the implementation I ended up with is pretty simple, we simply check that we haven't requested too many items to total and if we have, throw an ArgumentException. If we have't however, we remove all negative numbers, then we sort the positive numbers array and take the first however many requiredCount requested and sum them up. We also have a default requiredCount of 2 since the task description requested us to sum the lowest 2 items but we can change this to be whatever we want now, as can be seen in the tests.

Conclusions

I am really enjoying getting back into C# lately, it is much better than it used to be in terms of simplicity and ease of use, this is a basic implementation but you can see how powerful the language itself is and how descriptive and readable too. See you in the next one!

Top comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
jamesrweb profile image
James Robb

Could you write an example implementation proposition and the pros/cons you see between each implementation, i'd be interested to see what you mean in action. 😊