Skip to content
Katabench
Try free

Split the Tennis Score

Easy About 15 min Free, no account needed

The tennis kata: love, deuce and advantage in one long method.

The brief

TennisScore(p1, p2) announces a tennis game from the points won:

  • equal points: Love-All, Fifteen-All, Thirty-All, then Deuce from three-all on;
  • once someone has 4+ points: two ahead is Win for player1 (or 2), one ahead is Advantage player1 (or 2);
  • otherwise the running score, like Fifteen-Thirty (0 Love, 1 Fifteen, 2 Thirty, 3 Forty).

Refactor without changing behavior until every gate passes: the three phases (tied, endgame, running) each deserve a method, and the point names a lookup.

Starter code

C#
using System;

public class Solution
{
    // Spoken tennis score. One method speaks every phase of the game.
    public string TennisScore(int p1, int p2)
    {
        if (p1 == p2)
        {
            if (p1 == 0)
            {
                return "Love-All";
            }
            else if (p1 == 1)
            {
                return "Fifteen-All";
            }
            else if (p1 == 2)
            {
                return "Thirty-All";
            }
            else
            {
                return "Deuce";
            }
        }
        else if (p1 >= 4 || p2 >= 4)
        {
            var diff = p1 - p2;
            if (diff >= 2)
            {
                return "Win for player1";
            }
            else if (diff == 1)
            {
                return "Advantage player1";
            }
            else if (diff == -1)
            {
                return "Advantage player2";
            }
            else
            {
                return "Win for player2";
            }
        }
        else
        {
            var first = "";
            if (p1 == 0)
            {
                first = "Love";
            }
            else if (p1 == 1)
            {
                first = "Fifteen";
            }
            else if (p1 == 2)
            {
                first = "Thirty";
            }
            else
            {
                first = "Forty";
            }

            var second = "";
            if (p2 == 0)
            {
                second = "Love";
            }
            else if (p2 == 1)
            {
                second = "Fifteen";
            }
            else if (p2 == 2)
            {
                second = "Thirty";
            }
            else
            {
                second = "Forty";
            }

            return first + "-" + second;
        }
    }
}

How it is graded

Behavioral tests have to stay green while the grader measures complexity, nesting, method length, and duplication from your source.

C# refactoring exercises →

What it practices

Extract method
Pull named steps and named conditions out of a long method so each piece does one thing.
Table-driven logic
Replace branch ladders with data such as a rate table or lookup map.

Related katas