Avatar of ChrisPritchard

ChrisPritchard's solution

to Connect in the C# Track

Published at Oct 05 2018 · 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.

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.Linq;

public enum ConnectWinner { White, Black, None }

public class Connect
{
    private readonly string[] grid;

    public Connect(string[] input) => 
        grid = input.Select(o => o.Replace(" ", "")).ToArray();
    
    public ConnectWinner Result()
    {
        var startSets = Enumerable.Empty<(int, int)>();
        bool blackWin(int _, int col) => col == grid[0].Length - 1;
        bool whiteWin(int row, int _) => row == grid.Length - 1;

        if(Enumerable.Range(0, grid.Length).Where(r => 
            grid[r][0] == 'X').Any(r => 
                Crawl(startSets, r, 0, 'X', blackWin)))
            return ConnectWinner.Black;
            
        if(Enumerable.Range(0, grid[0].Length).Where(c => 
            grid[0][c] == 'O').Any(c => 
                Crawl(startSets, 0, c, 'O', whiteWin)))
            return ConnectWinner.White;

        return ConnectWinner.None;
    }

    private bool Crawl(IEnumerable<(int, int)> soFar, int row, int col, char target, Func<int, int, bool> hasWon)
    {
        if(row < 0 || row == grid.Length || col < 0 || col == grid[0].Length 
        || grid[row][col] != target || soFar.Contains((row, col)))
            return false;
        if(hasWon(row, col))
            return true;
        
        var newSoFar = soFar.Append((row, col));
        return new []
        {
            Crawl(newSoFar, row - 1, col, target, hasWon),
            Crawl(newSoFar, row + 1, col, target, hasWon),
            Crawl(newSoFar, row - 1, col + 1, target, hasWon),
            Crawl(newSoFar, row, col + 1, target, hasWon),
            Crawl(newSoFar, row + 1, col - 1, target, hasWon),
            Crawl(newSoFar, row, col - 1, target, hasWon)
        }.Any(o => o);
    }
}

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?