Avatar of artemkorsakov

artemkorsakov's solution

to Go Counting in the C# Track

Published at Apr 21 2019 · 0 comments
Instructions
Test suite
Solution

Count the scored points on a Go board.

In the game of go (also known as baduk, igo, cờ vây and wéiqí) points are gained by completely encircling empty intersections with your stones. The encircled intersections of a player are known as its territory.

Write a function that determines the territory of each player. You may assume that any stones that have been stranded in enemy territory have already been taken off the board.

Write a function that determines the territory which includes a specified coordinate.

Multiple empty intersections may be encircled at once and for encircling only horizontal and vertical neighbours count. In the following diagram the stones which matter are marked "O" and the stones that don't are marked "I" (ignored). Empty spaces represent empty intersections.

+----+
|IOOI|
|O  O|
|O OI|
|IOI |
+----+

To be more precise an empty intersection is part of a player's territory if all of its neighbours are either stones of that player or empty intersections that are part of that player's territory.

For more information see wikipedia or Sensei's Library.

Running the tests

To run the tests, run the command dotnet test from within the exercise directory.

Initially, only the first test will be enabled. This is to encourage you to solve the exercise one step at a time. Once you get the first test passing, remove the Skip property from the next test and work on getting that test passing. Once none of the tests are skipped and they are all passing, you can submit your solution using exercism submit GoCounting.cs

Further information

For more detailed information about the C# track, including how to get help if you're having trouble, please visit the exercism.io C# language page.

GoCountingTest.cs

// This file was auto-generated based on version 1.0.0 of the canonical data.

using System;
using System.Collections.Generic;
using Xunit;

public class GoCountingTest
{
    [Fact]
    public void Black_corner_territory_on_5x5_board()
    {
        var coordinate = (0, 1);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        var actual = sut.Territory(coordinate);
        var expected = (Owner.Black, new[] { (0, 0), (0, 1), (1, 0) });
        Assert.Equal(expected.Item1, actual.Item1);
        Assert.Equal(expected.Item2, actual.Item2);
    }

    [Fact(Skip = "Remove to run test")]
    public void White_center_territory_on_5x5_board()
    {
        var coordinate = (2, 3);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        var actual = sut.Territory(coordinate);
        var expected = (Owner.White, new[] { (2, 3) });
        Assert.Equal(expected.Item1, actual.Item1);
        Assert.Equal(expected.Item2, actual.Item2);
    }

    [Fact(Skip = "Remove to run test")]
    public void Open_corner_territory_on_5x5_board()
    {
        var coordinate = (1, 4);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        var actual = sut.Territory(coordinate);
        var expected = (Owner.None, new[] { (0, 3), (0, 4), (1, 4) });
        Assert.Equal(expected.Item1, actual.Item1);
        Assert.Equal(expected.Item2, actual.Item2);
    }

    [Fact(Skip = "Remove to run test")]
    public void A_stone_and_not_a_territory_on_5x5_board()
    {
        var coordinate = (1, 1);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        var actual = sut.Territory(coordinate);
        var expected = (Owner.None, Array.Empty<(int, int)>());
        Assert.Equal(expected.Item1, actual.Item1);
        Assert.Equal(expected.Item2, actual.Item2);
    }

    [Fact(Skip = "Remove to run test")]
    public void Invalid_because_x_is_too_low_for_5x5_board()
    {
        var coordinate = (-1, 1);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
    }

    [Fact(Skip = "Remove to run test")]
    public void Invalid_because_x_is_too_high_for_5x5_board()
    {
        var coordinate = (5, 1);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
    }

    [Fact(Skip = "Remove to run test")]
    public void Invalid_because_y_is_too_low_for_5x5_board()
    {
        var coordinate = (1, -1);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
    }

    [Fact(Skip = "Remove to run test")]
    public void Invalid_because_y_is_too_high_for_5x5_board()
    {
        var coordinate = (1, 5);
        var board = 
            "  B  \n" +
            " B B \n" +
            "B W B\n" +
            " W W \n" +
            "  W  ";
        var sut = new GoCounting(board);
        Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
    }

    [Fact(Skip = "Remove to run test")]
    public void One_territory_is_the_whole_board()
    {
        var board = " ";
        var sut = new GoCounting(board);
        var actual = sut.Territories();
        var expected = new Dictionary<Owner, (int, int)[]>
        {
            [Owner.Black] = Array.Empty<(int, int)>(),
            [Owner.White] = Array.Empty<(int, int)>(),
            [Owner.None] = new[] { (0, 0) }
        };
        Assert.Equal(expected.Keys, actual.Keys);
        Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
        Assert.Equal(expected[Owner.White], actual[Owner.White]);
        Assert.Equal(expected[Owner.None], actual[Owner.None]);
    }

    [Fact(Skip = "Remove to run test")]
    public void Two_territory_rectangular_board()
    {
        var board = 
            " BW \n" +
            " BW ";
        var sut = new GoCounting(board);
        var actual = sut.Territories();
        var expected = new Dictionary<Owner, (int, int)[]>
        {
            [Owner.Black] = new[] { (0, 0), (0, 1) },
            [Owner.White] = new[] { (3, 0), (3, 1) },
            [Owner.None] = Array.Empty<(int, int)>()
        };
        Assert.Equal(expected.Keys, actual.Keys);
        Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
        Assert.Equal(expected[Owner.White], actual[Owner.White]);
        Assert.Equal(expected[Owner.None], actual[Owner.None]);
    }

    [Fact(Skip = "Remove to run test")]
    public void Two_region_rectangular_board()
    {
        var board = " B ";
        var sut = new GoCounting(board);
        var actual = sut.Territories();
        var expected = new Dictionary<Owner, (int, int)[]>
        {
            [Owner.Black] = new[] { (0, 0), (2, 0) },
            [Owner.White] = Array.Empty<(int, int)>(),
            [Owner.None] = Array.Empty<(int, int)>()
        };
        Assert.Equal(expected.Keys, actual.Keys);
        Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
        Assert.Equal(expected[Owner.White], actual[Owner.White]);
        Assert.Equal(expected[Owner.None], actual[Owner.None]);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

public enum Owner
{
    Black,
    White,
    None
}

public class GoCounting
{
    private int xLimit;
    private int yLimit;
    private char[][] playerBoard;
    private List<GoTerritory> territories;
    private Dictionary<Owner, IEnumerable<(int, int)>> territoriesByOwner = new Dictionary<Owner, IEnumerable<(int, int)>>();

    public GoCounting(string board)
    {
        var rows = board.Split("\n");
        xLimit = rows[0].Length;
        yLimit = rows.Length;
        playerBoard = new char[yLimit][];
        for (int i = 0; i < rows.Length; i++)
        {
            playerBoard[i] = rows[i].ToCharArray();
        }
        territories = new List<GoTerritory>();
        for (int y = 0; y < yLimit; y++)
        {
            for (int x = 0; x < xLimit; x++)
            {
                if (playerBoard[y][x] == ' ' && GetGoTerritoryFromTerritories((x, y)) == null)
                {
                    territories.Add(new GoTerritory(this, (x, y)));
                }
            }
        }

        foreach (var owner in Enum.GetValues(typeof(Owner)))
        {
            var playerTerritory = new List<(int, int)>();
            foreach (var ter in territories.Where(t => t.GetOwner().Equals((Owner)owner)))
            {
                playerTerritory.AddRange(ter.territory);
            }
            territoriesByOwner.Add((Owner)owner, playerTerritory.ToArray());
        }
    }

    public Tuple<Owner, IEnumerable<(int, int)>> Territory((int, int) coord) => Tuple.Create(GetTerritoryOwner(coord), GetTerritory(coord));

    public Dictionary<Owner, IEnumerable<(int, int)>> Territories() => territoriesByOwner;

    private Owner GetTerritoryOwner((int, int) coord)
    {
        CheckCoordinates(coord);
        return GetGoTerritoryFromTerritories(coord)?.GetOwner() ?? Owner.None;
    }

    private IEnumerable<(int, int)> GetTerritory((int, int) coord)
    {
        CheckCoordinates(coord);
        return GetGoTerritoryFromTerritories(coord)?.territory.ToArray() ?? Array.Empty<(int, int)>();
    }

    private void CheckCoordinates((int, int) coord)
    {
        if (coord.Item1 < 0 || coord.Item2 < 0 || coord.Item1 >= xLimit || coord.Item2 >= yLimit)
        {
            throw new ArgumentException("Invalid coordinate");
        }
    }

    private GoTerritory GetGoTerritoryFromTerritories((int, int) coord) => territories.Where(t => t.territory.Contains(coord)).FirstOrDefault();

    private class GoTerritory
    {
        public List<(int, int)> territory = new List<(int, int)>();
        private List<Owner> borderOwners = new List<Owner>();
        private GoCounting goCounting;

        public GoTerritory(GoCounting goCounting, (int, int) pointStart)
        {
            this.goCounting = goCounting;
            territory.Add(pointStart);  // We believe that there is no stone at the start point.
            for (int i = 0; i < territory.Count; i++)
            {
                var currentPoint = territory[i];
                if (currentPoint.Item2 - 1 >= 0)
                {
                    ProcessPoint(currentPoint.Item1, currentPoint.Item2 - 1); // up
                }
                if (currentPoint.Item2 + 1 < goCounting.yLimit)
                {
                    ProcessPoint(currentPoint.Item1, currentPoint.Item2 + 1); // down
                }
                if (currentPoint.Item1 + 1 < goCounting.xLimit)
                {
                    ProcessPoint(currentPoint.Item1 + 1, currentPoint.Item2); // right
                }
                if (currentPoint.Item1 - 1 >= 0)
                {
                    ProcessPoint(currentPoint.Item1 - 1, currentPoint.Item2); // left
                }
            }
        }

        public Owner GetOwner() => borderOwners.Count == 0 || (borderOwners.Contains(Owner.Black) && borderOwners.Contains(Owner.White))
                ? Owner.None
                : borderOwners.Contains(Owner.Black) ? Owner.Black : Owner.White;

        private void ProcessPoint(int x, int y)
        {
            var point = (x, y);
            if (goCounting.playerBoard[y][x] == 'B')
            {
                borderOwners.Add(Owner.Black);
            }
            if (goCounting.playerBoard[y][x] == 'W')
            {
                borderOwners.Add(Owner.White);
            }
            if (goCounting.playerBoard[y][x] == ' ' && !territory.Contains(point))
            {
                territory.Add(point);
            }
        }
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?