Skip to content
Merged
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
18 changes: 18 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,24 @@
"strings"
],
"difficulty": 4
},
{
"slug": "alphametics",
"name": "Alphametics",
"uuid": "0c69f8bd-c99a-4cb2-b113-82deaf0915ee",
"practices": [
"auto",
"literals"
],
"prerequisites": [
"includes",
"namespaces",
"if-statements",
"booleans",
"headers",
"comparisons"
],
"difficulty": 6
}
],
"foregone": [
Expand Down
29 changes: 29 additions & 0 deletions exercises/practice/alphametics/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Instructions

Given an alphametics puzzle, find the correct solution.

[Alphametics][alphametics] is a puzzle where letters in words are replaced with numbers.

For example `SEND + MORE = MONEY`:

```text
S E N D
M O R E +
-----------
M O N E Y
```

Replacing these with valid numbers gives:

```text
9 5 6 7
1 0 8 5 +
-----------
1 0 6 5 2
```

This is correct because every letter is replaced by a different number and the words, translated into numbers, then make a valid sum.

Each letter must represent a different digit, and the leading digit of a multi-digit number must not be zero.

[alphametics]: https://en.wikipedia.org/wiki/Alphametics
19 changes: 19 additions & 0 deletions exercises/practice/alphametics/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"marcelweikum"
],
"files": {
"solution": [
"alphametics.cpp",
"alphametics.h"
],
"test": [
"alphametics_test.cpp"
],
"example": [
".meta/example.cpp",
".meta/example.h"
]
},
"blurb": "Given an alphametics puzzle, find the correct solution."
}
97 changes: 97 additions & 0 deletions exercises/practice/alphametics/.meta/example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#include <algorithm>
#include <functional>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>

#include "alphametics.h"

namespace alphametics {

std::optional<std::map<char, int>> solve(const std::string& puzzle) {
auto sep = puzzle.find("==");
if (sep == std::string::npos) return std::nullopt;
std::string left = puzzle.substr(0, sep);
std::string right = puzzle.substr(sep + 2);

auto trim = [&](std::string& s) {
auto b = s.find_first_not_of(' ');
auto e = s.find_last_not_of(' ');
s = (b == std::string::npos) ? std::string() : s.substr(b, e - b + 1);
};
trim(left);
trim(right);

std::vector<std::string> addends;
std::istringstream iss(left);
for (std::string part; std::getline(iss, part, '+');) {
trim(part);
addends.push_back(part);
}
trim(right);
std::string result = right;

std::vector<char> letters;
std::unordered_set<char> seen, leading;
auto collect = [&](const std::string& w) {
if (w.size() > 1) leading.insert(w.front());
for (char c : w) {
if (seen.insert(c).second) letters.push_back(c);
}
};
for (auto& w : addends) collect(w);
collect(result);
if (letters.size() > 10) return std::nullopt;

int n = letters.size();
std::map<char, int> idx;
for (int i = 0; i < n; ++i) idx[letters[i]] = i;
std::vector<long long> weight(n, 0);

for (auto& w : addends) {
long long mult = 1;
for (int i = (int)w.size() - 1; i >= 0; --i) {
weight[idx[w[i]]] += mult;
mult *= 10;
}
}
{
long long mult = 1;
for (int i = (int)result.size() - 1; i >= 0; --i) {
weight[idx[result[i]]] -= mult;
mult *= 10;
}
}

std::vector<bool> used(10, false);
std::map<char, int> assign;
bool found = false;
std::map<char, int> solution;
std::function<void(int, long long)> dfs = [&](int pos, long long sum) {
if (found) return;
if (pos == n) {
if (sum == 0) {
found = true;
solution = assign;
}
return;
}
char c = letters[pos];
for (int d = 0; d < 10 && !found; ++d) {
if (used[d] || (d == 0 && leading.count(c))) continue;
used[d] = true;
assign[c] = d;
dfs(pos + 1, sum + weight[pos] * d);
used[d] = false;
}
};

dfs(0, 0);
if (found) return solution;
return std::nullopt;
}

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

#include <map>
#include <optional>
#include <string>

namespace alphametics {

std::optional<std::map<char, int>> solve(const std::string& puzzle);

} // namespace alphametics
40 changes: 40 additions & 0 deletions exercises/practice/alphametics/.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.

[e0c08b07-9028-4d5f-91e1-d178fead8e1a]
description = "puzzle with three letters"

[a504ee41-cb92-4ec2-9f11-c37e95ab3f25]
description = "solution must have unique value for each letter"

[4e3b81d2-be7b-4c5c-9a80-cd72bc6d465a]
description = "leading zero solution is invalid"

[8a3e3168-d1ee-4df7-94c7-b9c54845ac3a]
description = "puzzle with two digits final carry"

[a9630645-15bd-48b6-a61e-d85c4021cc09]
description = "puzzle with four letters"

[3d905a86-5a52-4e4e-bf80-8951535791bd]
description = "puzzle with six letters"

[4febca56-e7b7-4789-97b9-530d09ba95f0]
description = "puzzle with seven letters"

[12125a75-7284-4f9a-a5fa-191471e0d44f]
description = "puzzle with eight letters"

[fb05955f-38dc-477a-a0b6-5ef78969fffa]
description = "puzzle with ten letters"

[9a101e81-9216-472b-b458-b513a7adacf7]
description = "puzzle with ten letters and 199 addends"
67 changes: 67 additions & 0 deletions exercises/practice/alphametics/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/alphametics/alphametics.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include "alphametics.h"

namespace alphametics {

// TODO: add your solution here

} // namespace alphametics
10 changes: 10 additions & 0 deletions exercises/practice/alphametics/alphametics.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#if !defined(ALPHAMETICS_H)
#define ALPHAMETICS_H

namespace alphametics {

// TODO: add your solution here

} // namespace alphametics

#endif // ALPHAMETICS_H
Loading