Skip to content

Added connect exercise #984

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,21 @@
"comparisons"
],
"difficulty": 6
},
{
"slug": "connect",
"name": "Connect",
"uuid": "86ba61cc-f88b-46b3-af2c-8ae304892cad",
"practices": [
"if-statements"
],
"prerequisites": [
"strings",
"vector-arrays",
"if-statements",
"loops"
],
"difficulty": 7
}
],
"foregone": [
Expand Down
27 changes: 27 additions & 0 deletions exercises/practice/connect/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Instructions

Compute the result for a game of Hex / Polygon.

The abstract boardgame known as [Hex][hex] / Polygon / CON-TAC-TIX is quite simple in rules, though complex in practice.
Two players place stones on a parallelogram with hexagonal fields.
The player to connect his/her stones to the opposite side first wins.
The four sides of the parallelogram 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 or the game's board might have a different width and height.)

The boards look like this:

```text
. 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.

[hex]: https://en.wikipedia.org/wiki/Hex_%28board_game%29
17 changes: 17 additions & 0 deletions exercises/practice/connect/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"authors": [],
"files": {
"solution": [
"connect.cpp",
"connect.h"
],
"test": [
"connect_test.cpp"
],
"example": [
".meta/example.cpp",
".meta/example.h"
]
},
"blurb": "Compute the result for a game of Hex / Polygon."
}
71 changes: 71 additions & 0 deletions exercises/practice/connect/.meta/example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include <queue>
#include <string>
#include <vector>

#include "connect.h"

namespace connect {

static const int dx[6] = {-1, -1, 0, 0, 1, 1};
static const int dy[6] = {0, 1, -1, 1, 0, -1};

std::string winner(const std::vector<std::string>& board) {
int n = board.size();
if (n == 0) return "";

std::vector<std::vector<char>> grid(n);
for (int i = 0; i < n; ++i) {
for (char c : board[i]) {
if (c != ' ') {
grid[i].push_back(c);
}
}
}
int m = grid[0].size();

auto bfs = [&](char player) {
std::vector<std::vector<bool>> vis(n, std::vector<bool>(m, false));
std::queue<std::pair<int, int>> q;

if (player == 'X') {
for (int i = 0; i < n; ++i) {
if (grid[i][0] == 'X') {
q.push({i, 0});
vis[i][0] = true;
}
}
} else {
for (int j = 0; j < m; ++j) {
if (grid[0][j] == 'O') {
q.push({0, j});
vis[0][j] = true;
}
}
}

while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
if ((player == 'X' && y == m - 1) ||
(player == 'O' && x == n - 1)) {
return true;
}
for (int d = 0; d < 6; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] &&
grid[nx][ny] == player) {
vis[nx][ny] = true;
q.push({nx, ny});
}
}
}
return false;
};

if (bfs('X')) return "X";
if (bfs('O')) return "O";
return "";
}

} // namespace connect
10 changes: 10 additions & 0 deletions exercises/practice/connect/.meta/example.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#pragma once

#include <string>
#include <vector>

namespace connect {

std::string winner(const std::vector<std::string>& board);

} // namespace connect
40 changes: 40 additions & 0 deletions exercises/practice/connect/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[6eff0df4-3e92-478d-9b54-d3e8b354db56]
description = "an empty board has no winner"

[298b94c0-b46d-45d8-b34b-0fa2ea71f0a4]
description = "X can win on a 1x1 board"

[763bbae0-cb8f-4f28-bc21-5be16a5722dc]
description = "O can win on a 1x1 board"

[819fde60-9ae2-485e-a024-cbb8ea68751b]
description = "only edges does not make a winner"

[2c56a0d5-9528-41e5-b92b-499dfe08506c]
description = "illegal diagonal does not make a winner"

[41cce3ef-43ca-4963-970a-c05d39aa1cc1]
description = "nobody wins crossing adjacent angles"

[cd61c143-92f6-4a8d-84d9-cb2b359e226b]
description = "X wins crossing from left to right"

[73d1eda6-16ab-4460-9904-b5f5dd401d0b]
description = "O wins crossing from top to bottom"

[c3a2a550-944a-4637-8b3f-1e1bf1340a3d]
description = "X wins using a convoluted path"

[17e76fa8-f731-4db7-92ad-ed2a285d31f3]
description = "X wins using a spiral path"
67 changes: 67 additions & 0 deletions exercises/practice/connect/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Get the exercise name from the current directory
get_filename_component(exercise ${CMAKE_CURRENT_SOURCE_DIR} NAME)

# Basic CMake project
cmake_minimum_required(VERSION 3.5.1)

# Name the project after the exercise
project(${exercise} CXX)

# Get a source filename from the exercise name by replacing -'s with _'s
string(REPLACE "-" "_" file ${exercise})

# Implementation could be only a header
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}.cpp)
set(exercise_cpp ${file}.cpp)
else()
set(exercise_cpp "")
endif()

# Use the common Catch library?
if(EXERCISM_COMMON_CATCH)
# For Exercism track development only
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h $<TARGET_OBJECTS:catchlib>)
elseif(EXERCISM_TEST_SUITE)
# The Exercism test suite is being run, the Docker image already
# includes a pre-built version of Catch.
find_package(Catch2 REQUIRED)
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h)
target_link_libraries(${exercise} PRIVATE Catch2::Catch2WithMain)
# When Catch is installed system wide we need to include a different
# header, we need this define to use the correct one.
target_compile_definitions(${exercise} PRIVATE EXERCISM_TEST_SUITE)
else()
# Build executable from sources and headers
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h test/tests-main.cpp)
endif()

set_target_properties(${exercise} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED OFF
CXX_EXTENSIONS OFF
)

set(CMAKE_BUILD_TYPE Debug)

if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(GNU|Clang)")
set_target_properties(${exercise} PROPERTIES
COMPILE_FLAGS "-Wall -Wextra -Wpedantic -Werror"
)
endif()

# Configure to run all the tests?
if(${EXERCISM_RUN_ALL_TESTS})
target_compile_definitions(${exercise} PRIVATE EXERCISM_RUN_ALL_TESTS)
endif()

# Tell MSVC not to warn us about unchecked iterators in debug builds
# Treat warnings as errors
# Treat type conversion warnings C4244 and C4267 as level 4 warnings, i.e. ignore them in level 3
if(${MSVC})
set_target_properties(${exercise} PROPERTIES
COMPILE_DEFINITIONS_DEBUG _SCL_SECURE_NO_WARNINGS
COMPILE_FLAGS "/WX /w44244 /w44267")
endif()

# Run the tests on every build
add_custom_target(test_${exercise} ALL DEPENDS ${exercise} COMMAND ${exercise})
7 changes: 7 additions & 0 deletions exercises/practice/connect/connect.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include "connect.h"

namespace connect {

// TODO: add your solution here

} // namespace connect
7 changes: 7 additions & 0 deletions exercises/practice/connect/connect.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once

namespace connect {

// TODO: add your solution here

} // namespace connect
81 changes: 81 additions & 0 deletions exercises/practice/connect/connect_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include "connect.h"
#ifdef EXERCISM_TEST_SUITE
#include <catch2/catch.hpp>
#else
#include "test/catch.hpp"
#endif

#include <string>
#include <vector>

TEST_CASE("an empty board has no winner",
"[6eff0df4-3e92-478d-9b54-d3e8b354db56]") {
std::vector<std::string> board = {". . . . .", " . . . . .", " . . . . .",
" . . . . .", " . . . . ."};
REQUIRE(connect::winner(board) == "");
}

TEST_CASE("X can win on a 1x1 board",
"[298b94c0-b46d-45d8-b34b-0fa2ea71f0a4]") {
std::vector<std::string> board = {"X"};
REQUIRE(connect::winner(board) == "X");
}

TEST_CASE("O can win on a 1x1 board",
"[763bbae0-cb8f-4f28-bc21-5be16a5722dc]") {
std::vector<std::string> board = {"O"};
REQUIRE(connect::winner(board) == "O");
}

TEST_CASE("only edges does not make a winner",
"[819fde60-9ae2-485e-a024-cbb8ea68751b]") {
std::vector<std::string> board = {"O O O X", " X . . X", " X . . X",
" X O O O"};
REQUIRE(connect::winner(board) == "");
}

TEST_CASE("illegal diagonal does not make a winner",
"[2c56a0d5-9528-41e5-b92b-499dfe08506c]") {
std::vector<std::string> board = {"X O . .", " O X X X", " O X O .",
" . O X .", " X X O O"};
REQUIRE(connect::winner(board) == "");
}

TEST_CASE("nobody wins crossing adjacent angles",
"[41cce3ef-43ca-4963-970a-c05d39aa1cc1]") {
std::vector<std::string> board = {"X . . .", " . X O .", " O . X O",
" . O . X", " . . O ."};
REQUIRE(connect::winner(board) == "");
}

TEST_CASE("X wins crossing from left to right",
"[cd61c143-92f6-4a8d-84d9-cb2b359e226b]") {
std::vector<std::string> board = {". O . .", " O X X X", " O X O .",
" X X O X", " . O X ."};
REQUIRE(connect::winner(board) == "X");
}

TEST_CASE("O wins crossing from top to bottom",
"[73d1eda6-16ab-4460-9904-b5f5dd401d0b]") {
std::vector<std::string> board = {". O . .", " O X X X", " O O O .",
" X X O X", " . O X ."};
REQUIRE(connect::winner(board) == "O");
}

TEST_CASE("X wins using a convoluted path",
"[c3a2a550-944a-4637-8b3f-1e1bf1340a3d]") {
std::vector<std::string> board = {". X X . .", " X . X . X", " . X . X .",
" . X X . .", " O O O O O"};
REQUIRE(connect::winner(board) == "X");
}

TEST_CASE("X wins using a spiral path",
"[17e76fa8-f731-4db7-92ad-ed2a285d31f3]") {
std::vector<std::string> board = {
"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"};
REQUIRE(connect::winner(board) == "X");
}
Loading