Avatar of cmccandless

cmccandless's solution

to Go Counting in the C# Track

Published at Jul 13 2018 · 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;
using System.Text;
using System.Threading.Tasks;

public enum Owner { None, Black, White, Disputed }
class GoCounting
{
	private static Dictionary<char, Owner> tokens = new Dictionary<char, Owner>
	{
		{' ',Owner.None},
		{'B',Owner.Black},
		{'W',Owner.White},
	};
	private Owner[][] board;
	private Dictionary<Owner, IEnumerable<Point>> territories = new Dictionary<Owner, IEnumerable<Point>>();
	public GoCounting(string board)
	{
		this.board = (from line in board.Split('\n')
						select line.Select(ch => tokens[ch]).ToArray()).ToArray();
	}
	public (Owner owner, (int, int)[] points) Territory((int x, int y) point)
	{
		var p = new Point(point);
		if (p.Y < 0 || p.Y >= board.Length || p.X < 0 || p.X >= board[p.Y].Length)
			throw new ArgumentException("out of range");
		if (board[p.Y][p.X] != Owner.None)
			return (Owner.None, Array.Empty<(int, int)>());
		var player = Owner.None;
		var border = new Dictionary<Point, Owner>();
		var pending = new HashSet<Point>();
		var invalid = new HashSet<Point>();
		var queue = new Queue<Point>();
		queue.Enqueue(p);
		while (queue.Any())
		{
			p = queue.Dequeue();
			if (board[p.Y][p.X] != Owner.None) continue;
			var n = p.Neighbors;
			var t = Owner.None;
			foreach (var x in n)
			{
				try { t |= board[x.Y][x.X]; }
				catch (IndexOutOfRangeException) { invalid.Add(x); }
			}
			switch (t)
			{
				case Owner.Disputed:
					player = t;
					goto case Owner.Black;
				case Owner.None:
					pending.Add(p);
					break;
				case Owner.Black:
				case Owner.White:
					border[p] = t;
					break;
			}
			foreach (var x in n.Except(invalid))
			{
				if (!border.ContainsKey(x) && !pending.Contains(x) &&
					!queue.Contains(x))
					queue.Enqueue(x);
			}
		}
		if (player == Owner.None)
		{
			try
			{
				var g = border.GroupBy(kvp => kvp.Value);
				player = g.Count() > 1 ? Owner.Disputed : g.First().Key;
			}
			catch (InvalidOperationException) { }
		}
		return (
			(Owner)((int) player % 3),
			pending.Union(border.Keys).Where(q =>
			{
				try { return board[q.Y][q.X] == Owner.None; }
				catch (IndexOutOfRangeException) { return false; }
			}).Select(q => q.AsTuple()).OrderBy(_p => _p).ToArray()
		);
	}
	public Dictionary<Owner, (int x, int y)[]> Territories()
	{
		var dict = new Dictionary<Owner, HashSet<(int, int)>>();
		dict[Owner.Black] = new HashSet<(int, int)>();
		dict[Owner.White] = new HashSet<(int, int)>();
		dict[Owner.None] = new HashSet<(int, int)>();
		var visited = new HashSet<(int, int)>();
		for (int y = 0; y < board.Length; y++)
			for (int x = 0; x < board[y].Length; x++)
			{
				var p = (x, y);
				if (visited.Contains(p)) continue;
				var (owner, points) = Territory(p);
				// if (owner != Owner.None)
				{
					foreach (var n in points)
					{
						dict[owner].Add(n);
						visited.Add(n);
					}
				}
				visited.Add(p);
			}
		return dict.ToDictionary(
			kvp => kvp.Key,
			kvp => kvp.Value.ToArray()
		);
	}
}
public class Point : IComparable<Point>, IEquatable<Point>
{
	public int X { get; set; }
	public int Y { get; set; }
	public Point((int x, int y) p)
	{
		this.X = p.x;
		this.Y = p.y;
	}
	// public Point(int x, int y)
	// {
	// 	this.X = x;
	// 	this.Y = y;
	// }
	public static Point operator +(Point a, Point b) => new Point((a.X + b.X, a.Y + b.Y));
	public static Point operator -(Point a, Point b) => new Point((a.X - b.X, a.Y - b.Y));
	public static readonly Point Origin = new Point((0, 0));
	public override string ToString() => $"({X},{Y})";
	private static int[] nums = new[] { -1, 0, 1 };
	private static Point[] neighborsRelative = (from x in nums
												from y in nums
												where (x == 0 || y == 0) && x != y
												select new Point((x, y))).ToArray();
	public HashSet<Point> Neighbors => new HashSet<Point>(from n in neighborsRelative select this + n);
	public int CompareTo(Point other)
	{
		var compare = this.X.CompareTo(other.X);
		if (compare != 0) return compare;
		return (compare << 16) + this.Y.CompareTo(other.Y);
	}
	public bool Equals(Point other) => this.X == other.X && this.Y == other.Y;
	public override bool Equals(object obj)
	{
		// var other = obj as Point;
		// return other != null && this.Equals(other);
		return obj is Point p && this.Equals(p);
	}
	public override int GetHashCode() => (this.X << 16) + this.Y;
	public (int x, int y) AsTuple() => (this.X, this.Y);
}

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?