Avatar of mikedamay

mikedamay's solution

to Connect in the C# Track

Published at Mar 05 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.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;

public enum ConnectWinner
{
    White = 'O',
    Black = 'X',
    None = 'X' + 1
}
public class Connect
{
    private struct Location
    {
        public bool Left { get; }
        public bool Top { get; }
        public bool Right { get; }
        public bool Bottom { get; }

        public Location(bool left, bool top, bool right, bool bottom)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
        }
    }

    private readonly ReadOnlyDictionary<Location, Func<(int col, int row), IEnumerable<(int col, int row)>>>
        board = new ReadOnlyDictionary<Location, Func<(int col, int row), IEnumerable<(int col, int row)>>>(
            new Dictionary<Location, Func<(int col, int row), IEnumerable<(int col, int row)>>>
            {
                {new Location(left :true, top: true, right: true, bottom: true), cc => new (int, int)[0]},
                {new Location(left :true, top: true, right: true, bottom: false), cc => throw new Exception()},
                {new Location(left :true, top: true, right: false, bottom: true), cc => throw new Exception()},
                {new Location(left :true, top: false, right: true, bottom: false), cc => throw new Exception()},
                {new Location(left :true, top: false, right: true, bottom: true), cc => throw new Exception()},
                {new Location(left :false, top: true, right: false, bottom: true), cc => throw new Exception()},
                {new Location(left :false, top: true, right: true, bottom: true), cc => throw new Exception()},
                {new Location(left :false, top: false, right: false, bottom: false), cc => FullHouse(cc)},
                {
                    new Location(left :true, top: true, right: false, bottom: false),
                    cc => new (int, int)[] {(cc.col + 2, cc.row), (cc.col + 1, cc.row + 1)}
                },
                {
                    new Location(left :false, top: false, right: true, bottom: true),
                    cc => new (int, int)[] {(cc.col - 2, cc.row), (cc.col - 1, cc.row - 1)}
                },
                {
                    new Location(left :false, top: true, right: true, bottom: false),
                    cc => new (int, int)[] {(cc.col - 2, cc.row), (cc.col - 1, cc.row + 1), (cc.col + 1, cc.row + 1)}
                },
                {
                    new Location(left :true, top: false, right: false, bottom: true),
                    cc => new (int, int)[] {(cc.col + 2, cc.row), (cc.col - 1, cc.row - 1), (cc.col + 1, cc.row - 1)}
                },
                {
                    new Location(left :true, top: false, right: false, bottom: false),
                    cc => new (int, int)[]
                    {
                        (cc.col + 2, cc.row), (cc.col + 1, cc.row + 1), (cc.col - 1, cc.row - 1),
                        (cc.col + 1, cc.row - 1)
                    }
                },
                {
                    new Location(left :false, top: true, right: false, bottom: false),
                    cc => new (int, int)[]
                        {(cc.col + 2, cc.row), (cc.col - 2, cc.row), (cc.col - 1, cc.row + 1), (cc.col + 1, cc.row + 1)}
                },
                {
                    new Location(left :false, top: false, right: true, bottom: false),
                    cc => new (int, int)[]
                    {
                        (cc.col - 2, cc.row), (cc.col - 1, cc.row - 1), (cc.col - 1, cc.row + 1),
                        (cc.col + 1, cc.row + 1)
                    }
                },
                {
                    new Location(left :false, top: false, right: false, bottom: true),
                    cc => new (int, int)[]
                        {(cc.col + 2, cc.row), (cc.col - 2, cc.row), (cc.col - 1, cc.row - 1), (cc.col + 1, cc.row - 1)}
                },
            });
    private ConnectWinner winner;
    public Connect(string[] input)
    {
        ISet<(int, int)> visited = new HashSet<(int, int)>();
        ImmutableHashSet<(int, int)> visit = ImmutableHashSet<(int, int)>.Empty;
        winner = input
            .LeftColumn()
            .Select((c, idx) => new {stone = c, idx})
            .Where(p => p.stone == (char) ConnectWinner.Black)
            .Any(p => IsWinner(p.stone, (p.idx, p.idx), input, visited))
            ? ConnectWinner.Black
            : input
                .First()
                .Select((c, idx) => new {stone = c, idx})
                .Where(p => p.stone == (char) ConnectWinner.White)
                .Any(p => IsWinner(p.stone, (p.idx, 0), input, visited))
                ? ConnectWinner.White
                : ConnectWinner.None;            
    }

    public ConnectWinner Result()
    {
        return winner;
    }

    
    private bool IsWinner(char stone, (int col, int row) coords, string[] input, ISet<(int, int)> visited)
    {
        MyDebug.Assert(input[coords.row][coords.col] == stone);
        visited.Add(coords);
        if (IsTargetEdge(stone, coords, input))
            return true;
        return Neighbours(coords, input).Where(cc => input[cc.row][cc.col] == stone)
            .Where(n => !visited.Contains(n))
            .Any(cc => IsWinner(stone, cc, input, visited));
    }

    private IEnumerable<(int col, int row)> Neighbours((int col, int row) coords, string[] input)
    {
        var location = new Location(IsLeftEdge(coords, input), IsTopEdge(coords, input)
            , IsRightEdge(coords, input), IsBottomEdge(coords, input));
        return this.board[location](coords);
    }

    private bool IsTargetEdge(char stone, (int col, int row) coords, string[] input)
      => stone == (char) ConnectWinner.Black
            ? IsRightEdge(coords, input)
            : IsBottomEdge(coords, input);

    /// <summary>
    /// returns neighbours for a non-edge stone 
    /// </summary>
    private static IEnumerable<(int col, int row)> FullHouse((int col, int row) coord)
    {
        yield return (coord.col - 1, coord.row - 1);
        yield return (coord.col + 1, coord.row - 1);
        yield return (coord.col - 2, coord.row);
        yield return (coord.col + 2, coord.row);
        yield return (coord.col - 1, coord.row + 1);
        yield return (coord.col + 1, coord.row + 1);
    }
    
    private bool IsRightEdge((int col, int row) coords, string[] input)
      => coords.col == BoardWidth(input) + coords.row - 1;

    private bool IsLeftEdge((int col, int row) coords, string[] input)
      => coords.col == coords.row;

    private bool IsTopEdge((int col, int row) coords, string[] input)
        => coords.row == 0;

    private bool IsBottomEdge((int col, int row) coords, string[] input)
        => coords.row == input.Length - 1;
    
    private int BoardWidth(string[] input) => input[0].Length;

}

public static class Extension
{
    public static IEnumerable<char> LeftColumn(this IEnumerable<string> input)
    {
        int row = 0;
        foreach (var line in input)
        {
            yield return line[row++];    // the offset in chars of the rhombus matches the row number
        }
    }
}

internal class MyDebug
{
    public static void Assert(bool b)
    {
        if (!b) throw new Exception();
    }
}

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?