Avatar of hamberge

hamberge's solution

to Connect in the C# Track

Published at Jul 28 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.

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;

public enum ConnectWinner
{
    White,
    Black,
    None
}

public class Connect
{
    private class BoardCell
    {
        public int x, y;
        public bool processed = false;
        public ConnectWinner cellOccupant;
        
        public void Reset()
        {
            processed = false;
        }
    }

    private const string _blackChar = "X";
    private const string _whiteChar = "O";
    private const string _noneChar = ".";
    private BoardCell[,] _board;
    private int _boardWidth;
    private int _boardHeight;

    private Queue<BoardCell> cellsToProcess = new Queue<BoardCell>();

    public Connect(string[] input)
    {
        _boardWidth = input[0].Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
        _boardHeight = input.Length;
        _board = new BoardCell[_boardWidth, _boardHeight];
        for(int y = 0; y < _boardHeight; y++)
        {
            string[] line = input[y].Split(' ', StringSplitOptions.RemoveEmptyEntries);
            for(int x = 0; x < _boardWidth; x++)
            {
                _board[x, y] = new BoardCell();
                _board[x, y].x = x;
                _board[x, y].y = y;
                if (line[x] == _blackChar)
                    _board[x, y].cellOccupant = ConnectWinner.Black;
                else if (line[x] == _whiteChar)
                    _board[x, y].cellOccupant = ConnectWinner.White;
                else if (line[x] == _noneChar)
                    _board[x, y].cellOccupant = ConnectWinner.None;
                else throw new ArgumentException("Board not properly formatted.");
            }
        }
    }
    
    private void ConditionalEnqueueAdjacentCell(BoardCell currentCell, BoardCell adjacentCell)
    {
        if(currentCell.cellOccupant == adjacentCell.cellOccupant && adjacentCell.processed == false)
        {
            cellsToProcess.Enqueue(adjacentCell);
        }
    }

    private bool processCell(BoardCell bc, ConnectWinner winner) 
    {
        switch (winner)
        {
            case ConnectWinner.White:
                if (bc.y == _boardHeight - 1)
                {
                    return true;
                }
                break;
            case ConnectWinner.Black:
                if (bc.x == _boardWidth - 1)
                {
                    return true;
                }
                break;
        }
        
        bool checkLeft = true, checkRight = true, checkUpLeft = true, checkUpRight = true, checkDownLeft = true, checkDownRight = true;
        if(bc.y == 0)
        {
            checkUpLeft = false;
            checkUpRight = false;
        }
        if(bc.x == 0)
        {
            checkDownLeft = false;
            checkLeft = false;
        }
        if(bc.x == _boardWidth-1)
        {
            checkUpRight = false;
            checkRight = false;
            checkDownRight = false;
        }
        if(bc.y == _boardHeight - 1)
        {
            checkDownLeft = false;
            checkDownRight = false;
        }
        if(checkDownRight)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x, bc.y + 1]);
        }
        if(checkDownLeft)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x - 1, bc.y + 1]);
        }
        if (checkRight)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x + 1, bc.y]);
        }
        if (checkLeft)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x - 1, bc.y]);
        }
        if (checkUpRight)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x + 1, bc.y - 1]);
        }
        if (checkUpLeft)
        {
            ConditionalEnqueueAdjacentCell(bc, _board[bc.x, bc.y - 1]);
        }
        
        bc.processed = true;
        return false;
    }

    public ConnectWinner Result()
    {
        for(int x = 0; x < _boardWidth; x++)
        {
            if(_board[x,0].cellOccupant == ConnectWinner.White)
            {
                cellsToProcess.Enqueue(_board[x, 0]);
            }
        }
        while (cellsToProcess.Count != 0)
        {
            if (processCell(cellsToProcess.Dequeue(), ConnectWinner.White))
            {
                return ConnectWinner.White;
            }
        }
        foreach(BoardCell bc in _board)
        {
            bc.Reset();
        }

        for(int y = 0; y < _boardHeight; y++)
        {
            if(_board[0,y].cellOccupant == ConnectWinner.Black)
            {
                cellsToProcess.Enqueue(_board[0, y]);
            }
        }
        while (cellsToProcess.Count != 0)
        {
            if (processCell(cellsToProcess.Dequeue(), ConnectWinner.Black))
            {
                return ConnectWinner.Black;
            }
        }
        return ConnectWinner.None;
    }
}

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?