Today is the first problem from CCC 2015. You’ll see quite a few code problems from there in the future. I noticed the CCC problem set tends to over complicate the problem description. Allow me to restate it in a much simpler, clearer, and easier to understand version.

Summary of Zero That Out: Positive integers are provided from input one at a time. Every input that is a 0 ignores the last given input (a series of n 0s means ignore the last series of n inputs). The program should keep track of the inputs and output the final sum of all values that were not ignored.

Tests I started by writing tests for a summation class (very simple). The second series of tests verifies that zero inputs ignores the last input. I started with the most degenerate cases where there are no inputs, to 1 input, to multiple inputs, and ignoring multiple values. I didn’t write a longer acceptance tests because this can be eyeballed to deduce that it works for all cases.

[TestFixture]
public class TestZeroThatOut
{
    private ZeroOutNumberSequence sequence;
    [SetUp]
    public void Setup()
    {
        sequence = new ZeroOutNumberSequence();
    }
    [Test]
    public void AcceptingValuesShouldProvideCorrectSum()
    {
        Assert.That(sequence.Sum(), Is.EqualTo(0));
        VerifyAcceptedValueSum(1, 1);
        VerifyAcceptedValueSum(1, 2);
        VerifyAcceptedValueSum(2, 4);
    }
    [Test]
    public void AcceptingZeroShouldEraseLastSum()
    {
        VerifyAcceptedValueSum(0, 0);
        VerifyAcceptedValueSum(0, 0);
        VerifyAcceptedValueSum(1, 1);
        VerifyAcceptedValueSum(0, 0);
        VerifyAcceptedValueSum(1, 1);
        VerifyAcceptedValueSum(1, 2);
        VerifyAcceptedValueSum(2, 4);
        VerifyAcceptedValueSum(0, 2);
        VerifyAcceptedValueSum(5, 7);
        VerifyAcceptedValueSum(14, 21);
        VerifyAcceptedValueSum(0, 7);
        VerifyAcceptedValueSum(0, 2);
        VerifyAcceptedValueSum(0, 1);
        VerifyAcceptedValueSum(0, 0);
    }
    private void VerifyAcceptedValueSum(int value, int sum)
    {
        sequence.Accept(value);
        Assert.That(sequence.Sum(), Is.EqualTo(sum));
    }
}

Solution I started out with just an int sum. Then it became an List which kept track of the sums. Then I initialized the list with the first element with a sum value of 0, so I don’t have to keep checking for empty list everywhere in the code.

public class ZeroOutNumberSequence
{
    private int sum;
    private List<int> sums = new List<int>();
}
public ZeroOutNumberSequence()
{
    sums.Add(0);
}
public int Sum()
{
    return sums[sums.Count – 1];
}
public void Accept(int value)
{
    if (value == 0 && sums.Count != 1)
        sums.RemoveAt(sums.Count – 1);
    else
        sums.Add(value + Sum());
}

This one’s a bit too simple. I’ll be following up the #2 (Jersey) problem next week. It’s a more interesting problem and worth a good TDD walkthrough.

Blog Comments powered by Disqus.

Next Post Previous Post