 # ErikSchierboom's solution

## to Go Counting in the C# Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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.

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.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### GoCountingTest.cs

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

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

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, new ValueTuple<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, ValueTuple<int,int>[]>
{
[Owner.Black] = new ValueTuple<int,int>,
[Owner.White] = new ValueTuple<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, ValueTuple<int,int>[]>
{
[Owner.Black] = new[] { (0, 0), (0, 1) },
[Owner.White] = new[] { (3, 0), (3, 1) },
[Owner.None] = new ValueTuple<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, ValueTuple<int,int>[]>
{
[Owner.Black] = new[] { (0, 0), (2, 0) },
[Owner.White] = new ValueTuple<int,int>,
[Owner.None] = new ValueTuple<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.Drawing;
using System.Collections.Generic;
using System.Linq;

public class GoCounting
{
public enum Player
{
None,
Black,
White
}

public GoCounting(string input)
{
board = ParseBoard(input);
}

private static Player CharToPlayer(char c)
{
switch (c)
{
case 'B': return Player.Black;
case 'W': return Player.White;
default: return Player.None;
}
}

private static Player[][] ParseBoard(string input)
{
var split = input.Split('\n');
var rows = split.Length;
var cols = split.Length;

return split.Select(row => row.Select(CharToPlayer).ToArray()).ToArray();
}

private int Cols => board.Length;
private int Rows => board.Length;

private bool IsValidCoordinate(Point coordinate) =>
coordinate.Y >= 0 && coordinate.Y < Rows &&
coordinate.X >= 0 && coordinate.X < Cols;

private Player GetPlayer(Point coordinate) => board[coordinate.Y][coordinate.X];

private bool isEmpty(Point coordinate) => GetPlayer(coordinate) == Player.None;
private bool isTaken(Point coordinate) => !isEmpty(coordinate);

private IEnumerable<Point> EmptyCoordinates()
{
return Enumerable.Range(0, Cols).SelectMany(col =>
Enumerable.Range(0, Rows).Select(row => new Point(col, row)))
.Where(isEmpty);
}

private IEnumerable<Point> NeighborCoordinates(Point coordinate)
{
var row = coordinate.Y;
var col = coordinate.X;

var coords = new[]
{
new Point(col, row - 1),
new Point(col-1, row),
new Point(col+1, row),
new Point(col, row+1)
};

return coords.Where(IsValidCoordinate);
}

private IEnumerable<Point> NonEmptyNeighborCoordinates(Point coordinate) =>
NeighborCoordinates(coordinate).Where(neighborCoordinate => !isEmpty(neighborCoordinate));

private IEnumerable<Point> EmptyNeighborCoordinates(Point coordinate) =>
NeighborCoordinates(coordinate).Where(isEmpty);

private Player TerritoryOwner(HashSet<Point> coords)
{
var neighborColors = coords.SelectMany(NonEmptyNeighborCoordinates).Where(isTaken).Select(GetPlayer);
var uniqueNeighborColors = ToSet(neighborColors);

if (uniqueNeighborColors.Count == 1)
return uniqueNeighborColors.First();

return Player.None;
}

private HashSet<Point> TerritoryHelper(HashSet<Point> remainder, HashSet<Point> acc)
{
if (!remainder.Any())
return acc;

var emptyNeighbors = new HashSet<Point>(remainder.SelectMany(EmptyNeighborCoordinates));
emptyNeighbors.ExceptWith(acc);

var newAcc = ToSet(acc);
newAcc.UnionWith(emptyNeighbors);
return TerritoryHelper(emptyNeighbors, newAcc);
}

private HashSet<Point> Territory(Point coordinate) =>
IsValidCoordinate(coordinate) && isEmpty(coordinate)
? TerritoryHelper(ToSingletonSet(coordinate), ToSingletonSet(coordinate))
: new HashSet<Point>();

public Tuple<Player, IEnumerable<Point>> TerritoryFor(Point coord)
{
var coords = Territory(coord);
if (!coords.Any())
return null;

var owner = TerritoryOwner(coords);
return Tuple.Create(owner, coords.AsEnumerable());
}

private Dictionary<Player, IEnumerable<Point>> TerritoriesHelper(HashSet<Point> remainder, Dictionary<Player, IEnumerable<Point>> acc)
{
if (!remainder.Any())
return acc;

var coord = remainder.First();
var coords = Territory(coord);
var owner = TerritoryOwner(coords);

var newRemainder = ToSet(remainder);
newRemainder.ExceptWith(coords);

var newAcc = new Dictionary<Player, IEnumerable<Point>>(acc);
newAcc[owner] = coords;

return TerritoriesHelper(newRemainder, newAcc);
}

public Dictionary<Player, IEnumerable<Point>> Territories()
{
var emptyCoords = EmptyCoordinates();
return TerritoriesHelper(ToSet(emptyCoords), new Dictionary<Player, IEnumerable<Point>>());
}

private static HashSet<T> ToSet<T>(IEnumerable<T> value) => new HashSet<T>(value);
private static HashSet<T> ToSingletonSet<T>(T value) => new HashSet<T> { value };
}``````