Avatar of toronacii

toronacii's solution

to Connect in the C# Track

Published at Mar 07 2019 · 0 comments
Instructions
Test suite
Solution

Compute the result for a game of Hex / Polygon.

The abstract boardgame known as Hex / Polygon / CON-TAC-TIX is quite simple in rules, though complex in practice. Two players place stones on a rhombus with hexagonal fields. The player to connect his/her stones to the opposite side first wins. The four sides of the rhombus are divided between the two players (i.e. one player gets assigned a side and the side directly opposite it and the other player gets assigned the two other sides).

Your goal is to build a program that given a simple representation of a board computes the winner (or lack thereof). Note that all games need not be "fair". (For example, players may have mismatched piece counts.)

The boards look like this (with spaces added for readability, which won't be in the representation passed to your code):

. O . X .
 . X X O .
  O O O X .
   . X O X O
    X O O O X

"Player O" plays from top to bottom, "Player X" plays from left to right. In the above example O has made a connection from left to right but nobody has won since O didn't connect top and bottom.

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 Connect.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.

Submitting Incomplete Solutions

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

ConnectTest.cs

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

using Xunit;

public class ConnectTest
{
    [Fact]
    public void An_empty_board_has_no_winner()
    {
        var board = new[]
        {
            ". . . . .",
            " . . . . .",
            "  . . . . .",
            "   . . . . .",
            "    . . . . ."
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.None, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void X_can_win_on_a_1x1_board()
    {
        var board = new[]
        {
            "X"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.Black, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void O_can_win_on_a_1x1_board()
    {
        var board = new[]
        {
            "O"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.White, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void Only_edges_does_not_make_a_winner()
    {
        var board = new[]
        {
            "O O O X",
            " X . . X",
            "  X . . X",
            "   X O O O"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.None, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void Illegal_diagonal_does_not_make_a_winner()
    {
        var board = new[]
        {
            "X O . .",
            " O X X X",
            "  O X O .",
            "   . O X .",
            "    X X O O"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.None, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void Nobody_wins_crossing_adjacent_angles()
    {
        var board = new[]
        {
            "X . . .",
            " . X O .",
            "  O . X O",
            "   . O . X",
            "    . . O ."
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.None, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void X_wins_crossing_from_left_to_right()
    {
        var board = new[]
        {
            ". O . .",
            " O X X X",
            "  O X O .",
            "   X X O X",
            "    . O X ."
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.Black, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void O_wins_crossing_from_top_to_bottom()
    {
        var board = new[]
        {
            ". O . .",
            " O X X X",
            "  O O O .",
            "   X X O X",
            "    . O X ."
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.White, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void X_wins_using_a_convoluted_path()
    {
        var board = new[]
        {
            ". X X . .",
            " X . X . X",
            "  . X . X .",
            "   . X X . .",
            "    O O O O O"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.Black, sut.Result());
    }

    [Fact(Skip = "Remove to run test")]
    public void X_wins_using_a_spiral_path()
    {
        var board = new[]
        {
            "O X X X X X X X X",
            " O X O O O O O O O",
            "  O X O X X X X X O",
            "   O X O X O O O X O",
            "    O X O X X X O X O",
            "     O X O O O X O X O",
            "      O X X X X X O X O",
            "       O O O O O O O X O",
            "        X X X X X X X X O"
        };
        var sut = new Connect(board);
        Assert.Equal(ConnectWinner.Black, sut.Result());
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Connect
{
    private readonly Board board;

    public Connect(string[] input)
    {
        board = Board.Initialize(input);
    }
    
    public ConnectWinner Result()
    {
        var playerOne = new Player(ConnectWinner.Black, ConnectPosition.Left, ConnectPosition.Right);
        var playerTwo = new Player(ConnectWinner.White, ConnectPosition.Top, ConnectPosition.Bottom);

        if (playerOne.Win(board))
        {
            return playerOne.Color;
        }
        else if (playerTwo.Win(board))
        {
            return playerTwo.Color;
        }

        return ConnectWinner.None;
    }
}

public class Board : List<Box>
{
    private readonly string[] input;
    private Dictionary<string, Box> boxes;

    private Board(string[] input) : base()
    {
        this.input = input;
        boxes = new Dictionary<string, Box>();
    }

    public static Board Initialize(string[] input)
    {
        return new Board(input).Initialize();
    }

    private Board Initialize()
    {
        for (var i = 0; i < input.Length; i++)
        {
            for (var j = 0; j < input[i].Length; j++)
            {
                var value = input[i][j];

                if (Box.IsValid(value))
                {
                    var box = GetOrCreateBox(i, j);

                    GetOrCreateBox(i - 1, j - 1)?.AddAdjacent(box);
                    GetOrCreateBox(i - 1, j + 1)?.AddAdjacent(box);
                    GetOrCreateBox(i, j - 2)?.AddAdjacent(box);
                    GetOrCreateBox(i, j + 2)?.AddAdjacent(box);
                    GetOrCreateBox(i + 1, j - 1)?.AddAdjacent(box);
                    GetOrCreateBox(i + 1, j + 1)?.AddAdjacent(box);

                    Add(box);
                }
            }
        }

        return this;
    }

    private Box GetOrCreateBox(int i, int j)
    {
        Box box = null;

        if (i >= 0 && i < input.Length && j >= 0 && j < input[i].Length && Box.IsValid(input[i][j]))
        {
            var index = i.ToString() + j;

            if (!boxes.ContainsKey(index))
            {
                ConnectPosition positions = ConnectPosition.Center;

                if (i == 0) positions = ConnectPosition.Top;
                if (j - i == 0) positions |= ConnectPosition.Left;
                if (i == input.Length - 1) positions |= ConnectPosition.Bottom;
                if (j == input[i].Length - 1) positions |= ConnectPosition.Right;

                boxes[index] = new Box(input[i][j], positions, index);
            }

            box = boxes[index];
        }

        return box;
    }
}

public class Player
{
    private readonly ConnectPosition origin;
    private readonly ConnectPosition destiny;

    public Player(ConnectWinner color, ConnectPosition origin, ConnectPosition destiny)
    {
        Color = color;

        this.origin = origin;
        this.destiny = destiny;
    }

    public ConnectWinner Color { get; }

    public bool Win(Board board)
    {
        var originBoxes = board.Where(box => box.Color == Color && box.HasPosition(origin));

        foreach (var box in originBoxes)
        {
            var boxes = box.GetLastBoxes();

            if (boxes.Any(b => b.HasPosition(destiny)))
            {
                return true;
            }
        }

        return false;
    }
}

public class Box
{
    private static readonly Dictionary<char, ConnectWinner> values = new Dictionary<char, ConnectWinner>
    {
        ['X'] = ConnectWinner.Black,
        ['O'] = ConnectWinner.White,
        ['.'] = ConnectWinner.None
    };

    private readonly char value;
    private readonly ConnectPosition positions;
    private readonly string name;
    private List<Box> adjacents;

    public ConnectWinner Color => values[value];

    public Box(char value, ConnectPosition positions, string name)
    {
        this.value = value;
        this.positions = positions;
        this.name = name;
        adjacents = new List<Box>();
    }

    public void AddAdjacent(Box adjacent)
    {
        adjacents.Add(adjacent);
    }

    public IEnumerable<Box> GetLastBoxes()
    {
        return GetLastBoxes(this, new HashSet<Box>(), new HashSet<Box> { this });
    }

    private HashSet<Box> GetLastBoxes(Box box, HashSet<Box> boxes, HashSet<Box> omit)
    {
        var adjacents = box.adjacents
            .Where(b => b.Color == box.Color)
            .Except(omit);

        if (!adjacents.Any())
        {
            boxes.Add(box);
        }

        foreach (var adjacent in adjacents)
        {
            omit.Add(adjacent);
            GetLastBoxes(adjacent, boxes, omit);
        }

        return boxes;
    }

    public bool HasPosition(ConnectPosition position)
    {
        return positions.HasFlag(position);
    }

    public static bool IsValid(char value)
    {
        return values.ContainsKey(value);
    }

    public override string ToString()
    {
        return $"{ name }; { value }; { Color }; { positions }";
    }
}

public enum ConnectWinner
{
    White,
    Black,
    None
}

[Flags]
public enum ConnectPosition
{
    Center = 0,
    Top = 1,
    Bottom = 2,
    Right = 4,
    Left = 8
}

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?