Home >

SWE101 TDD GreeGame challenge

2. March 2010

Last weekend I attended the Software Engineering 101 event at the Microsoft Offices in Nashville. It was a lot of fun and at the end we did some pair programming to try out Test Driven Development. Here is the solution that @mhenry07 and me came up with.

 

    public class GreedGame
    {
        private const int MaxDieValue = 6;
        private const int SingleOneValue = 100;
        private const int SingleFiveValue = 50;
        private const int TripleOnesScore = 1000;
        private const int TripleMultiplier = 100;

        public int Score(int[] dice)
        {
            int[] diceValueCounts = GetDiceValueCounts(dice);
            return CalculateScore(diceValueCounts);
        }

        private int CalculateScore(int[] diceValueCounts)
        {
            int score = 0;
            for (var dieValue = 1; dieValue <= MaxDieValue; dieValue++)
            {
                var count = GetCount(dieValue, diceValueCounts);

                score += CalculateNonTripletScore(dieValue, count);

                if (count >= 3)
                {
                    score += CalculateTripletScore(dieValue);
                }
            }
            return score;
        }

        private int[] GetDiceValueCounts(int[] dice)
        {
            int[] diceValueCounts = new int[] { 0, 0, 0, 0, 0, 0 };

            foreach (var die in dice)
            {
                diceValueCounts[die - 1]++;
            }
            return diceValueCounts;
        }

        private int CalculateNonTripletScore(int dieValue, int count)
        {
            int multiplier = count < 3 ? count : count - 3;
            if (dieValue == 1)
            {
                return multiplier * SingleOneValue;
            }
            if (dieValue == 5)
            {
                return multiplier * SingleFiveValue;
            }
            return 0;
        }

        private int CalculateTripletScore(int dieValue)
        {
            if (dieValue == 1)
            {
                return TripleOnesScore;
            }
            return dieValue * TripleMultiplier;
        }

        private int GetCount(int number, int[] numberCounts)
        {
            return numberCounts[number - 1];
        }
    }

 

Nice, succint, readable. I was surprised at how the whole thing came together as we put tests together and refactored the code.