Update some 2015 sources to .clang-tidy

This commit is contained in:
2021-12-02 19:57:58 +00:00
parent 7ab7ecb00a
commit 9ecc3ff53d
27 changed files with 305 additions and 336 deletions

View File

@@ -8,65 +8,69 @@
# misc-no-recursion: We do not mind recursion (and we need to recurse) # misc-no-recursion: We do not mind recursion (and we need to recurse)
# readability-function-cognitive-complexity: Too many asserts trigger this one unnecessarily # readability-function-cognitive-complexity: Too many asserts trigger this one unnecessarily
# cppcoreguidelines-pro-bounds-array-to-pointer-decay: Triggers on assert() # cppcoreguidelines-pro-bounds-array-to-pointer-decay: Triggers on assert()
Checks: >- Checks: >-
*, *,
-abseil-*, -abseil-*,
-altera-*, -altera-*,
-android-*, -android-*,
-fuchsia-*, -fuchsia-*,
-hicpp-*, -hicpp-*,
-llvmlibc-*, -llvmlibc-*,
-objc-*, -objc-*,
-zircon-*, -zircon-*,
-cppcoreguidelines-owning-memory, -cppcoreguidelines-owning-memory,
-cppcoreguidelines-pro-type-vararg, -cppcoreguidelines-pro-type-vararg,
-google-runtime-references, -google-runtime-references,
-llvm-header-guard, -llvm-header-guard,
-misc-no-recursion, -misc-no-recursion,
-readability-function-cognitive-complexity, -readability-function-cognitive-complexity,
-clang-diagnostic-ignored-optimization-argument, -clang-diagnostic-ignored-optimization-argument,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay -cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-readability-identifier-length,
-cppcoreguidelines-avoid-magic-numbers,
-readability-magic-numbers,
-misc-non-private-member-variables-in-classes
WarningsAsErrors: '*,-clang-diagnostic-ignored-optimization-argument' WarningsAsErrors: '*,-clang-diagnostic-ignored-optimization-argument'
HeaderFilterRegex: '' HeaderFilterRegex: ''
AnalyzeTemporaryDtors: false AnalyzeTemporaryDtors: false
FormatStyle: file FormatStyle: file
User: mgrettondann User: mgrettondann
CheckOptions: CheckOptions:
- key: llvm-else-after-return.WarnOnConditionVariables - key: llvm-else-after-return.WarnOnConditionVariables
value: '0' value: '0'
- key: modernize-loop-convert.MinConfidence - key: modernize-loop-convert.MinConfidence
value: reasonable value: reasonable
- key: modernize-replace-auto-ptr.IncludeStyle - key: modernize-replace-auto-ptr.IncludeStyle
value: llvm value: llvm
- key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons
value: '0' value: '0'
- key: google-readability-namespace-comments.ShortNamespaceLines - key: google-readability-namespace-comments.ShortNamespaceLines
value: '10' value: '10'
- key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField
value: '0' value: '0'
- key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: '1' value: '1'
- key: cert-dcl16-c.NewSuffixes - key: cert-dcl16-c.NewSuffixes
value: 'L;LL;LU;LLU' value: 'L;LL;LU;LLU'
- key: google-readability-braces-around-statements.ShortStatementLines - key: google-readability-braces-around-statements.ShortStatementLines
value: '1' value: '1'
- key: modernize-pass-by-value.IncludeStyle - key: modernize-pass-by-value.IncludeStyle
value: llvm value: llvm
- key: google-readability-namespace-comments.SpacesBeforeComments - key: google-readability-namespace-comments.SpacesBeforeComments
value: '2' value: '2'
- key: modernize-loop-convert.MaxCopySize - key: modernize-loop-convert.MaxCopySize
value: '16' value: '16'
- key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors
value: '1' value: '1'
- key: modernize-use-nullptr.NullMacros - key: modernize-use-nullptr.NullMacros
value: 'NULL' value: 'NULL'
- key: llvm-qualified-auto.AddConstToQualified - key: llvm-qualified-auto.AddConstToQualified
value: '0' value: '0'
- key: modernize-loop-convert.NamingStyle - key: modernize-loop-convert.NamingStyle
value: CamelCase value: CamelCase
- key: llvm-else-after-return.WarnOnUnfixable - key: llvm-else-after-return.WarnOnUnfixable
value: '0' value: '0'
- key: google-readability-function-size.StatementThreshold - key: google-readability-function-size.StatementThreshold
value: '800' value: '800'
... ...

View File

@@ -2,13 +2,14 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
int floor = 0; int floor = 0;
for (auto c : line) { for (auto c : line) { // NOLINT(readability-identifier-length)
assert(c == '(' || c == ')'); assert(c == '(' || c == ')');
floor += (c == '(') - (c == ')'); floor += (c == '(') ? 1 : 0;
floor -= (c == ')') ? 1 : 0;
} }
std::cout << floor << "\n"; std::cout << floor << "\n";
} }

View File

@@ -2,15 +2,16 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
int floor = 0; int floor = 0;
std::string::size_type pos = 0; std::string::size_type pos = 0;
for (auto c : line) { for (auto c : line) { // NOLINT(readability-identifier-length)
++pos; ++pos;
assert(c == '(' || c == ')'); assert(c == '(' || c == ')');
floor += (c == '(') - (c == ')'); floor += (c == '(') ? 1 : 0;
floor -= (c == ')') ? 1 : 0;
if (floor == -1) { if (floor == -1) {
break; break;
} }

View File

@@ -8,7 +8,7 @@ struct Box
/** Construct box. /** Construct box.
* \param s String representation of dimensions 'lxwxh' * \param s String representation of dimensions 'lxwxh'
*/ */
Box(std::string const& s) explicit Box(std::string const& s)
{ {
std::size_t pos = 0; std::size_t pos = 0;
l_ = std::stoul(s, &pos, 10); l_ = std::stoul(s, &pos, 10);
@@ -22,22 +22,22 @@ struct Box
} }
// How much paper does this box need? // How much paper does this box need?
unsigned long paper_needed() const [[nodiscard]] auto paper_needed() const -> std::uint64_t
{ {
unsigned long s1 = l_ * w_; std::uint64_t s1 = l_ * w_;
unsigned long s2 = w_ * h_; std::uint64_t s2 = w_ * h_;
unsigned long s3 = h_ * l_; std::uint64_t s3 = h_ * l_;
return 2 * (s1 + s2 + s3) + std::min({s1, s2, s3}); return 2 * (s1 + s2 + s3) + std::min({s1, s2, s3});
} }
unsigned long l_; std::uint64_t l_;
unsigned long w_; std::uint64_t w_;
unsigned long h_; std::uint64_t h_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
unsigned long total = 0; std::uint64_t total = 0;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
Box b(line); Box b(line);
auto amount = b.paper_needed(); auto amount = b.paper_needed();

View File

@@ -6,9 +6,9 @@
struct Box struct Box
{ {
/** Construct box. /** Construct box.
* \param s String representation of dimensions 'lxwxh' * \param s String representation of dimensions `lxwxh`
*/ */
Box(std::string const& s) explicit Box(std::string const& s)
{ {
std::size_t pos = 0; std::size_t pos = 0;
l_ = std::stoul(s, &pos, 10); l_ = std::stoul(s, &pos, 10);
@@ -22,33 +22,33 @@ struct Box
} }
// How much paper does this box need? // How much paper does this box need?
unsigned long paper_needed() const [[nodiscard]] auto paper_needed() const -> std::uint64_t
{ {
unsigned long s1 = l_ * w_; auto s1{l_ * w_};
unsigned long s2 = w_ * h_; auto s2{w_ * h_};
unsigned long s3 = h_ * l_; auto s3{h_ * l_};
return 2 * (s1 + s2 + s3) + std::min({s1, s2, s3}); return 2 * (s1 + s2 + s3) + std::min({s1, s2, s3});
} }
// How much ribbon do we need? // How much ribbon do we need?
unsigned long ribbon_needed() const [[nodiscard]] auto ribbon_needed() const -> std::uint64_t
{ {
// The various side perimeters - we want the min of these multiplied by // The various side perimeters - we want the min of these multiplied by
// volume. // volume.
unsigned long p1 = 2 * (l_ + w_); auto p1{2 * (l_ + w_)};
unsigned long p2 = 2 * (w_ + h_); auto p2{2 * (w_ + h_)};
unsigned long p3 = 2 * (h_ + l_); auto p3{2 * (h_ + l_)};
return l_ * w_ * h_ + std::min({p1, p2, p3}); return l_ * w_ * h_ + std::min({p1, p2, p3});
} }
unsigned long l_; std::uint64_t l_;
unsigned long w_; std::uint64_t w_;
unsigned long h_; std::uint64_t h_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
unsigned long total = 0; std::uint64_t total = 0;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
Box b(line); Box b(line);
auto amount = b.ribbon_needed(); auto amount = b.ribbon_needed();

View File

@@ -1,19 +1,17 @@
#include <algorithm> #include <algorithm>
#include <cassert>
#include <iostream> #include <iostream>
#include <set> #include <set>
#include <string>
struct Pos struct Pos
{ {
Pos(int x, int y) : x_(x), y_(y) {} Pos(int x, int y) : x_(x), y_(y) {} // NOLINT(bugprone-easily-swappable-parameters)
bool operator<(Pos const& rhs) const noexcept auto operator<(Pos const& rhs) const noexcept -> bool
{ {
return x_ < rhs.x_ || (x_ == rhs.x_ && y_ < rhs.y_); return x_ < rhs.x_ || (x_ == rhs.x_ && y_ < rhs.y_);
} }
bool operator==(Pos const& rhs) const noexcept { return x_ == rhs.x_ && y_ == rhs.y_; } auto operator==(Pos const& rhs) const noexcept -> bool { return x_ == rhs.x_ && y_ == rhs.y_; }
void move(char c) void move(char c)
{ {
@@ -40,7 +38,7 @@ struct Pos
int y_; int y_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::set<Pos> visited; std::set<Pos> visited;

View File

@@ -1,19 +1,17 @@
#include <algorithm> #include <algorithm>
#include <cassert>
#include <iostream> #include <iostream>
#include <set> #include <set>
#include <string>
struct Pos struct Pos
{ {
Pos(int x, int y) : x_(x), y_(y) {} Pos(int x, int y) : x_(x), y_(y) {} // NOLINT(bugprone-easily-swappable-parameters)
bool operator<(Pos const& rhs) const noexcept auto operator<(Pos const& rhs) const noexcept -> bool
{ {
return x_ < rhs.x_ || (x_ == rhs.x_ && y_ < rhs.y_); return x_ < rhs.x_ || (x_ == rhs.x_ && y_ < rhs.y_);
} }
bool operator==(Pos const& rhs) const noexcept { return x_ == rhs.x_ && y_ == rhs.y_; } auto operator==(Pos const& rhs) const noexcept -> bool { return x_ == rhs.x_ && y_ == rhs.y_; }
void move(char c) noexcept void move(char c) noexcept
{ {
@@ -40,25 +38,25 @@ struct Pos
int y_; int y_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::set<Pos> visited; std::set<Pos> visited;
Pos santa(0, 0); Pos santa(0, 0);
Pos robo_santa(0, 0); Pos robot_santa(0, 0);
visited.insert(santa); visited.insert(santa);
visited.insert(robo_santa); visited.insert(robot_santa);
bool do_robo = false; bool do_robot = false;
for (auto c : line) { for (auto c : line) {
if (do_robo) { if (do_robot) {
robo_santa.move(c); robot_santa.move(c);
visited.insert(robo_santa); visited.insert(robot_santa);
} }
else { else {
santa.move(c); santa.move(c);
visited.insert(santa); visited.insert(santa);
} }
do_robo = !do_robo; do_robot = !do_robot;
} }
std::cout << "Houses visited = " << visited.size() << "\n"; std::cout << "Houses visited = " << visited.size() << "\n";
} }

View File

@@ -1,27 +1,27 @@
#include <algorithm> #include <algorithm>
#include <array>
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <set>
#include <string> #include <string>
#include <openssl/evp.h> #include <openssl/evp.h>
using MD5Digest = unsigned char[EVP_MAX_MD_SIZE]; using MD5Digest = std::array<unsigned char, EVP_MAX_MD_SIZE>;
unsigned int md5(MD5Digest digest, std::string const& s) auto md5(MD5Digest& digest, std::string const& s) -> unsigned int
{ {
EVP_MD const* md{EVP_md5()}; EVP_MD const* md{EVP_md5()};
unsigned int md_len; unsigned int md_len{0};
EVP_MD_CTX* md_ctxt{EVP_MD_CTX_new()}; EVP_MD_CTX* md_context{EVP_MD_CTX_new()};
assert(md_ctxt != NULL); assert(md_context != nullptr);
EVP_DigestInit_ex2(md_ctxt, md, NULL); EVP_DigestInit_ex2(md_context, md, nullptr);
EVP_DigestUpdate(md_ctxt, s.data(), s.length()); EVP_DigestUpdate(md_context, s.data(), s.length());
EVP_DigestFinal_ex(md_ctxt, digest, &md_len); EVP_DigestFinal_ex(md_context, digest.data(), &md_len);
return md_len; return md_len;
} }
bool is_valid(std::string const& s) auto is_valid(std::string const& s) -> bool
{ {
MD5Digest digest; MD5Digest digest;
auto len = md5(digest, s); auto len = md5(digest, s);
@@ -29,7 +29,7 @@ bool is_valid(std::string const& s)
return digest[0] == 0 && digest[1] == 0 && (digest[2] & 0xf0) == 0; return digest[0] == 0 && digest[1] == 0 && (digest[2] & 0xf0) == 0;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
unsigned i = 0; unsigned i = 0;

View File

@@ -1,27 +1,27 @@
#include <algorithm> #include <algorithm>
#include <array>
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <set>
#include <string> #include <string>
#include <openssl/evp.h> #include <openssl/evp.h>
using MD5Digest = unsigned char[EVP_MAX_MD_SIZE]; using MD5Digest = std::array<unsigned char, EVP_MAX_MD_SIZE>;
unsigned int md5(MD5Digest digest, std::string const& s) auto md5(MD5Digest& digest, std::string const& s) -> unsigned int
{ {
EVP_MD const* md{EVP_md5()}; EVP_MD const* md{EVP_md5()};
unsigned int md_len; unsigned int md_len{0};
EVP_MD_CTX* md_ctxt{EVP_MD_CTX_new()}; EVP_MD_CTX* md_context{EVP_MD_CTX_new()};
assert(md_ctxt != NULL); assert(md_context != nullptr);
EVP_DigestInit_ex2(md_ctxt, md, NULL); EVP_DigestInit_ex2(md_context, md, nullptr);
EVP_DigestUpdate(md_ctxt, s.data(), s.length()); EVP_DigestUpdate(md_context, s.data(), s.length());
EVP_DigestFinal_ex(md_ctxt, digest, &md_len); EVP_DigestFinal_ex(md_context, digest.data(), &md_len);
return md_len; return md_len;
} }
bool is_valid(std::string const& s) auto is_valid(std::string const& s) -> bool
{ {
MD5Digest digest; MD5Digest digest;
auto len = md5(digest, s); auto len = md5(digest, s);
@@ -29,7 +29,7 @@ bool is_valid(std::string const& s)
return digest[0] == 0 && digest[1] == 0 && digest[2] == 0; return digest[0] == 0 && digest[1] == 0 && digest[2] == 0;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
unsigned i = 0; unsigned i = 0;

View File

@@ -1,7 +1,5 @@
#include <algorithm> #include <algorithm>
#include <cassert>
#include <iostream> #include <iostream>
#include <set>
#include <string> #include <string>
// Check if a string is nice: // Check if a string is nice:
@@ -9,7 +7,7 @@
// >=3 vowels // >=3 vowels
// At least one double letter // At least one double letter
// No instances of 'ab', 'cd', 'pq', or 'xy'. // No instances of 'ab', 'cd', 'pq', or 'xy'.
bool is_nice(std::string const& s) noexcept auto is_nice(std::string const& s) noexcept -> bool
{ {
unsigned vowel_count = 0; unsigned vowel_count = 0;
bool repeated = false; bool repeated = false;
@@ -33,7 +31,7 @@ bool is_nice(std::string const& s) noexcept
return repeated && vowel_count >= 3; return repeated && vowel_count >= 3;
} }
int main(int argc, char** argv) auto main() -> int
{ {
unsigned nice_strings; unsigned nice_strings;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {

View File

@@ -1,21 +1,19 @@
#include <algorithm> #include <algorithm>
#include <cassert>
#include <iostream> #include <iostream>
#include <set>
#include <string> #include <string>
// Check if a string is nice: // Check if a string is nice:
// Nice strings have: // Nice strings have:
// repeated double letters - but not overlapping // repeated double letters - but not overlapping
// repeated letters separated by one other. // repeated letters separated by one other.
bool is_nice(std::string const& s) noexcept auto is_nice(std::string const& s) noexcept -> bool
{ {
bool repeated_pair = false; bool repeated_pair = false;
bool repeated_sep = false; bool repeated_sep = false;
std::cout << s; std::cout << s;
for (std::string::size_type i = 0; i < s.length() - 2; ++i) { for (std::string::size_type i = 0; i < s.length() - 2; ++i) {
// Find whether the two characters starting at i are repeated in the rest of // Find whether the two characters starting at `i` are repeated in the rest of
// the string. We don't have to look backwards as we will already have // the string. We don't have to look backwards as we will already have
// scanned it. // scanned it.
if (s.substr(i + 2).find(s.substr(i, 2)) != std::string::npos) { if (s.substr(i + 2).find(s.substr(i, 2)) != std::string::npos) {
@@ -35,11 +33,11 @@ bool is_nice(std::string const& s) noexcept
return repeated_pair && repeated_sep; return repeated_pair && repeated_sep;
} }
int main(int argc, char** argv) auto main() -> int
{ {
unsigned nice_strings; unsigned nice_strings{0};
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
nice_strings += is_nice(line); nice_strings += is_nice(line) ? 1 : 0;
} }
std::cout << nice_strings << '\n'; std::cout << nice_strings << '\n';

View File

@@ -2,7 +2,6 @@
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <regex> #include <regex>
#include <set>
#include <string> #include <string>
enum class Action { TurnOn, Toggle, TurnOff }; enum class Action { TurnOn, Toggle, TurnOff };
@@ -12,9 +11,9 @@ using Point = std::pair<unsigned, unsigned>;
/// A command /// A command
struct Command struct Command
{ {
Command(std::string const& s) explicit Command(std::string const& s)
{ {
const char* re = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)"; const char* re = R"((turn on|toggle|turn off)\s(\d+),(\d+)\sthrough\s(\d+),(\d+))";
std::smatch m; std::smatch m;
if (!std::regex_search(s, m, std::regex(re))) { if (!std::regex_search(s, m, std::regex(re))) {
std::cerr << "Unable to interpret:" << s << "\n"; std::cerr << "Unable to interpret:" << s << "\n";
@@ -51,7 +50,7 @@ struct Array
{ {
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
lights_[i][j] = false; lights_[i][j] = false; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
} }
} }
@@ -68,13 +67,14 @@ struct Array
for (unsigned j = command.bottom_left_.second; j <= command.top_right_.second; ++j) { for (unsigned j = command.bottom_left_.second; j <= command.top_right_.second; ++j) {
switch (command.act_) { switch (command.act_) {
case Action::TurnOn: case Action::TurnOn:
lights_[i][j] = true; lights_[i][j] = true; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
break; break;
case Action::Toggle: case Action::Toggle:
lights_[i][j] = !lights_[i][j]; lights_[i][j] = // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
!lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
break; break;
case Action::TurnOff: case Action::TurnOff:
lights_[i][j] = false; lights_[i][j] = false; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
break; break;
} }
} }
@@ -82,12 +82,12 @@ struct Array
} }
/// How many lights are on /// How many lights are on
unsigned num_on() const noexcept [[nodiscard]] auto num_on() const noexcept -> unsigned
{ {
unsigned count = 0; unsigned count = 0;
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
count += lights_[i][j]; count += lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
} }
@@ -100,7 +100,9 @@ struct Array
std::cout << "P1\n" << N << " " << N << "\n"; std::cout << "P1\n" << N << " " << N << "\n";
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
std::cout << (lights_[i][j] ? "1" : "0"); std::cout << (lights_[i][j] // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
? "1"
: "0"); // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
if (j % 70 == 0) { if (j % 70 == 0) {
std::cout << "\n"; std::cout << "\n";
} }
@@ -109,10 +111,10 @@ struct Array
} }
} }
bool lights_[N][N]; bool lights_[N][N]{}; // NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
}; };
int main(int argc, char** argv) auto main() -> int
{ {
Array<1000> arr; Array<1000> arr;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {

View File

@@ -2,16 +2,15 @@
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <regex> #include <regex>
#include <set>
#include <string> #include <string>
enum class Action { TurnOn, Toggle, TurnOff }; enum class Action { TurnOn, Toggle, TurnOff };
using Point = std::pair<unsigned, unsigned>; using Point = std::pair<unsigned, unsigned>;
struct Command struct Command
{ {
Command(std::string const& s) explicit Command(std::string const& s)
{ {
const char* re = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)"; const char* re = R"((turn on|toggle|turn off)\s(\d+),(\d+)\sthrough\s(\d+),(\d+))";
std::smatch m; std::smatch m;
if (!std::regex_search(s, m, std::regex(re))) { if (!std::regex_search(s, m, std::regex(re))) {
std::cerr << "Unable to interpret:" << s << "\n"; std::cerr << "Unable to interpret:" << s << "\n";
@@ -47,7 +46,7 @@ struct Array
{ {
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
lights_[i][j] = 0; lights_[i][j] = 0; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
} }
} }
@@ -63,14 +62,14 @@ struct Array
for (unsigned j = command.bottom_left_.second; j <= command.top_right_.second; ++j) { for (unsigned j = command.bottom_left_.second; j <= command.top_right_.second; ++j) {
switch (command.act_) { switch (command.act_) {
case Action::TurnOn: case Action::TurnOn:
++lights_[i][j]; ++lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
break; break;
case Action::Toggle: case Action::Toggle:
lights_[i][j] += 2; lights_[i][j] += 2; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
break; break;
case Action::TurnOff: case Action::TurnOff:
if (lights_[i][j] > 0) { if (lights_[i][j] > 0) { // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
--lights_[i][j]; --lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
break; break;
} }
@@ -78,12 +77,12 @@ struct Array
} }
} }
unsigned brightness() const noexcept [[nodiscard]] auto brightness() const noexcept -> unsigned
{ {
unsigned count = 0; unsigned count = 0;
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
count += lights_[i][j]; count += lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
} }
return count; return count;
@@ -95,23 +94,24 @@ struct Array
unsigned max = 0; unsigned max = 0;
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
if (lights_[i][j] > max) { if (lights_[i][j] > max) { // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
max = lights_[i][j]; max = lights_[i][j]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
} }
} }
} }
std::cout << "P2\n" << N << " " << N << "\n" << max << "\n"; std::cout << "P2\n" << N << " " << N << "\n" << max << "\n";
for (unsigned i = 0; i < N; ++i) { for (unsigned i = 0; i < N; ++i) {
for (unsigned j = 0; j < N; ++j) { for (unsigned j = 0; j < N; ++j) {
std::cout << lights_[i][j] << "\n"; std::cout << lights_[i][j] // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
<< "\n";
} }
} }
} }
unsigned lights_[N][N]; unsigned lights_[N][N]{}; // NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
}; };
int main(int argc, char** argv) auto main() -> int
{ {
Array<1000> arr; Array<1000> arr;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {

View File

@@ -44,7 +44,7 @@ enum class Action {
}; };
/// Pretty-print action /// Pretty-print action
std::ostream& operator<<(std::ostream& os, Action act) auto operator<<(std::ostream& os, Action act) -> std::ostream&
{ {
switch (act) { switch (act) {
case Action::Set: case Action::Set:
@@ -74,7 +74,7 @@ using Wire = std::string; ///< Wire name (string)
using Signal = std::variant<Value, Wire>; ///< Either a wire or explicit value using Signal = std::variant<Value, Wire>; ///< Either a wire or explicit value
/// Outputter for a signal /// Outputter for a signal
std::ostream& operator<<(std::ostream& os, Signal const& signal) auto operator<<(std::ostream& os, Signal const& signal) -> std::ostream&
{ {
return std::visit( return std::visit(
[&os](auto&& arg) -> std::ostream& { [&os](auto&& arg) -> std::ostream& {
@@ -97,10 +97,10 @@ struct Instruction
* set := signal '->' wire * set := signal '->' wire
* not := 'NOT' set * not := 'NOT' set
* op := 'AND' | 'OR' | 'LSHIFT' | 'RSHIFT' * op := 'AND' | 'OR' | 'LSHIFT' | 'RSHIFT'
* binop := signal op signal '->' wire * bin-op := signal op signal '->' wire
* instr := binop | not | set * instr := bin-op | not | set
*/ */
Instruction(std::string const& s) explicit Instruction(std::string const& s)
{ {
if (parse_bin_op(s)) { if (parse_bin_op(s)) {
return; return;
@@ -116,16 +116,16 @@ struct Instruction
} }
/// Get action /// Get action
Action action() const noexcept { return act_; } [[nodiscard]] auto action() const noexcept -> Action { return act_; }
/// Get the destination wire /// Get the destination wire
Wire const& dest() const noexcept { return dest_; } [[nodiscard]] auto dest() const noexcept -> Wire const& { return dest_; }
/// Get the first (or only) source /// Get the first (or only) source
Signal const& src1() const noexcept { return src1_; } [[nodiscard]] auto src1() const noexcept -> Signal const& { return src1_; }
/// Get the second source /// Get the second source
Signal const& src2() const noexcept [[nodiscard]] auto src2() const noexcept -> Signal const&
{ {
assert(act_ != Action::Set && act_ != Action::Not); assert(act_ != Action::Set && act_ != Action::Not);
return src2_; return src2_;
@@ -133,7 +133,7 @@ struct Instruction
private: private:
/// Parse a <not> instruction. Return true if successful. /// Parse a <not> instruction. Return true if successful.
bool parse_not(std::string const& s) auto parse_not(std::string const& s) -> bool
{ {
if (s.substr(0, 4) == "NOT ") { if (s.substr(0, 4) == "NOT ") {
std::string::size_type pos = 4; std::string::size_type pos = 4;
@@ -146,7 +146,7 @@ private:
} }
/// Parse a <bin_op> instruction. Return true if successful. /// Parse a <bin_op> instruction. Return true if successful.
bool parse_bin_op(std::string const& s) auto parse_bin_op(std::string const& s) -> bool
{ {
static const std::regex re("^([[:lower:][:digit:]]+) ([[:upper:]]+) " static const std::regex re("^([[:lower:][:digit:]]+) ([[:upper:]]+) "
"([[:lower:][:digit:]]+) -> ([[:lower:]]+)"); "([[:lower:][:digit:]]+) -> ([[:lower:]]+)");
@@ -181,7 +181,7 @@ private:
/// ///
/// Also used for the latter half of <not> parsing. ACT tells you what is /// Also used for the latter half of <not> parsing. ACT tells you what is
/// being parsed. Returns true if parsing successful. /// being parsed. Returns true if parsing successful.
bool parse_set(std::string const& s, Action act = Action::Set) auto parse_set(std::string const& s, Action act = Action::Set) -> bool
{ {
static const std::regex re("^([[:lower:][:digit:]]+) -> ([[:lower:]]+)"); static const std::regex re("^([[:lower:][:digit:]]+) -> ([[:lower:]]+)");
std::smatch m; std::smatch m;
@@ -196,25 +196,23 @@ private:
} }
/// Make a Signal from a string. /// Make a Signal from a string.
Signal make_signal(std::string const& s) static auto make_signal(std::string const& s) -> Signal
{ {
if (std::isdigit(s[0])) { if (std::isdigit(s[0]) == 1) {
auto u = std::stoul(s, nullptr, 10); auto u = std::stoul(s, nullptr, 10);
assert(u <= UINT16_MAX); assert(u <= UINT16_MAX);
return Signal(static_cast<std::uint16_t>(u)); return {static_cast<std::uint16_t>(u)};
}
else {
return Signal(s);
} }
return {s};
} }
Action act_; ///< Action Action act_{Action::Not}; ///< Action
Wire dest_; ///< Destination wire Wire dest_; ///< Destination wire
Signal src1_, src2_; ///< Source signals Signal src1_, src2_; ///< Source signals
}; };
/// Outputter for an instruction. /// Outputter for an instruction.
std::ostream& operator<<(std::ostream& os, Instruction const& instr) auto operator<<(std::ostream& os, Instruction const& instr) -> std::ostream&
{ {
os << instr.action() << " " << instr.dest() << ", " << instr.src1(); os << instr.action() << " " << instr.dest() << ", " << instr.src1();
if (instr.action() != Action::Set && instr.action() != Action::Not) { if (instr.action() != Action::Set && instr.action() != Action::Not) {
@@ -230,27 +228,31 @@ using Instructions = std::vector<Instruction>; ///< Instructions to execute
struct VM struct VM
{ {
/// Add an instruction the the list we have /// Add an instruction the the list we have
void add_instr(Instruction const& instr) { instrs_.push_back(instr); } void add_instr(Instruction const& instr) { instructions_.push_back(instr); }
/// Has this wire a known value? /// Has this wire a known value?
bool has_value(Wire const& w) const noexcept { return values_.find(w) != values_.end(); } [[nodiscard]] auto has_value(Wire const& w) const noexcept -> bool
{
return values_.find(w) != values_.end();
}
/// Has this signal a known value? /// Has this signal a known value?
bool has_value(Signal const& s) const noexcept [[nodiscard]] auto has_value(Signal const& s) const noexcept -> bool
{ {
return std::visit( return std::visit(Overloaded{[]([[maybe_unused]] Value v) { return true; },
Overloaded{[](Value v) { return true; }, [&](Wire const& w) { return has_value(w); }}, s); [&](Wire const& w) { return has_value(w); }},
s);
} }
/// Get the value on the wire /// Get the value on the wire
Value value(Wire const& w) const noexcept [[nodiscard]] auto value(Wire const& w) const noexcept -> Value
{ {
assert(has_value(w)); assert(has_value(w));
return values_.find(w)->second; return values_.find(w)->second;
} }
/// Get the value of a signal /// Get the value of a signal
Value value(Signal const& s) const noexcept [[nodiscard]] auto value(Signal const& s) const noexcept -> Value
{ {
return std::visit( return std::visit(
Overloaded{[](Value v) { return v; }, [&](Wire const& w) { return value(w); }}, s); Overloaded{[](Value v) { return v; }, [&](Wire const& w) { return value(w); }}, s);
@@ -267,15 +269,17 @@ struct VM
void value(Signal const& s, Value v) void value(Signal const& s, Value v)
{ {
std::visit( std::visit(
Overloaded{[v](Value v2) { assert(v == v2); }, [&, v](Wire const& w) { value(w, v); }}, s); Overloaded{[v](Value v2) { assert(v == v2); }, // NOLINT(bugprone-lambda-function-name)
[&, v](Wire const& w) { value(w, v); }}, // NOLINT(bugprone-lambda-function-name)
s); // NOLINT(bugprone-lambda-function-name)
} }
/// Execute the instructions. Returns true if we have updated some wire /// Execute the instructions. Returns true if we have updated some wire
/// values. /// values.
bool execute() auto execute() -> bool
{ {
bool done_anything = false; bool done_anything = false;
for (auto const& instr : instrs_) { for (auto const& instr : instructions_) {
done_anything |= execute_instr(instr); done_anything |= execute_instr(instr);
} }
@@ -290,13 +294,13 @@ private:
* An instruction may not be executed if the incoming signals have not been * An instruction may not be executed if the incoming signals have not been
* set yet. * set yet.
*/ */
bool execute_instr(Instruction const& instr) auto execute_instr(Instruction const& instr) -> bool
{ {
std::cout << instr << " # "; std::cout << instr << " # ";
// First of all check there is something to do - i.e. that the destination // First check there is something to do - i.e. that the destination
// register has not been set already. // register has not been set already.
Wire dest = instr.dest(); auto const& dest{instr.dest()};
if (has_value(dest)) { if (has_value(dest)) {
std::cout << "already has value: " << dest << " = " << value(dest) << "\n"; std::cout << "already has value: " << dest << " = " << value(dest) << "\n";
return false; return false;
@@ -325,10 +329,10 @@ private:
* \param fn How to modify the source value to the dest. * \param fn How to modify the source value to the dest.
* \return True if we executed the function. * \return True if we executed the function.
*/ */
bool execute_single_src(Instruction const& instr, std::function<Value(Value)> fn) auto execute_single_src(Instruction const& instr, const std::function<Value(Value)>& fn) -> bool
{ {
Wire dest = instr.dest(); auto const& dest{instr.dest()};
Signal src = instr.src1(); Signal const& src{instr.src1()};
if (has_value(src)) { if (has_value(src)) {
value(dest, fn(value(src))); value(dest, fn(value(src)));
std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n"; std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n";
@@ -344,11 +348,12 @@ private:
* \param fn How to modify the source values to the dest. * \param fn How to modify the source values to the dest.
* \return True if we executed the function. * \return True if we executed the function.
*/ */
bool execute_double_src(Instruction const& instr, std::function<Value(Value, Value)> fn) auto execute_double_src(Instruction const& instr, const std::function<Value(Value, Value)>& fn)
-> bool
{ {
Wire dest = instr.dest(); auto const& dest{instr.dest()};
Signal src1 = instr.src1(); auto const& src1{instr.src1()};
Signal src2 = instr.src2(); auto const& src2{instr.src2()};
if (has_value(src1) && has_value(src2)) { if (has_value(src1) && has_value(src2)) {
value(dest, fn(value(src1), value(src2))); value(dest, fn(value(src1), value(src2)));
std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n"; std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n";
@@ -360,10 +365,10 @@ private:
} }
ValueMap values_; ValueMap values_;
Instructions instrs_; Instructions instructions_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
VM vm; VM vm;

View File

@@ -44,7 +44,7 @@ enum class Action {
}; };
/// Pretty-print action /// Pretty-print action
std::ostream& operator<<(std::ostream& os, Action act) auto operator<<(std::ostream& os, Action act) -> std::ostream&
{ {
switch (act) { switch (act) {
case Action::Set: case Action::Set:
@@ -74,7 +74,7 @@ using Wire = std::string; ///< Wire name (string)
using Signal = std::variant<Value, Wire>; ///< Either a wire or explicit value using Signal = std::variant<Value, Wire>; ///< Either a wire or explicit value
/// Outputter for a signal /// Outputter for a signal
std::ostream& operator<<(std::ostream& os, Signal const& signal) auto operator<<(std::ostream& os, Signal const& signal) -> std::ostream&
{ {
return std::visit( return std::visit(
[&os](auto&& arg) -> std::ostream& { [&os](auto&& arg) -> std::ostream& {
@@ -100,7 +100,7 @@ struct Instruction
* binop := signal op signal '->' wire * binop := signal op signal '->' wire
* instr := binop | not | set * instr := binop | not | set
*/ */
Instruction(std::string const& s) explicit Instruction(std::string const& s)
{ {
if (parse_bin_op(s)) { if (parse_bin_op(s)) {
return; return;
@@ -116,16 +116,16 @@ struct Instruction
} }
/// Get action /// Get action
Action action() const noexcept { return act_; } [[nodiscard]] auto action() const noexcept -> Action { return act_; }
/// Get the destination wire /// Get the destination wire
Wire const& dest() const noexcept { return dest_; } [[nodiscard]] auto dest() const noexcept -> Wire const& { return dest_; }
/// Get the first (or only) source /// Get the first (or only) source
Signal const& src1() const noexcept { return src1_; } [[nodiscard]] auto src1() const noexcept -> Signal const& { return src1_; }
/// Get the second source /// Get the second source
Signal const& src2() const noexcept [[nodiscard]] auto src2() const noexcept -> Signal const&
{ {
assert(act_ != Action::Set && act_ != Action::Not); assert(act_ != Action::Set && act_ != Action::Not);
return src2_; return src2_;
@@ -133,7 +133,7 @@ struct Instruction
private: private:
/// Parse a <not> instruction. Return true if successful. /// Parse a <not> instruction. Return true if successful.
bool parse_not(std::string const& s) auto parse_not(std::string const& s) -> bool
{ {
if (s.substr(0, 4) == "NOT ") { if (s.substr(0, 4) == "NOT ") {
std::string::size_type pos = 4; std::string::size_type pos = 4;
@@ -146,7 +146,7 @@ private:
} }
/// Parse a <bin_op> instruction. Return true if successful. /// Parse a <bin_op> instruction. Return true if successful.
bool parse_bin_op(std::string const& s) auto parse_bin_op(std::string const& s) -> bool
{ {
static const std::regex re("^([[:lower:][:digit:]]+) ([[:upper:]]+) " static const std::regex re("^([[:lower:][:digit:]]+) ([[:upper:]]+) "
"([[:lower:][:digit:]]+) -> ([[:lower:]]+)"); "([[:lower:][:digit:]]+) -> ([[:lower:]]+)");
@@ -181,7 +181,7 @@ private:
/// ///
/// Also used for the latter half of <not> parsing. ACT tells you what is /// Also used for the latter half of <not> parsing. ACT tells you what is
/// being parsed. Returns true if parsing successful. /// being parsed. Returns true if parsing successful.
bool parse_set(std::string const& s, Action act = Action::Set) auto parse_set(std::string const& s, Action act = Action::Set) -> bool
{ {
static const std::regex re("^([[:lower:][:digit:]]+) -> ([[:lower:]]+)"); static const std::regex re("^([[:lower:][:digit:]]+) -> ([[:lower:]]+)");
std::smatch m; std::smatch m;
@@ -196,25 +196,23 @@ private:
} }
/// Make a Signal from a string. /// Make a Signal from a string.
Signal make_signal(std::string const& s) static auto make_signal(std::string const& s) -> Signal
{ {
if (std::isdigit(s[0])) { if (std::isdigit(s[0]) == 1) {
auto u = std::stoul(s, nullptr, 10); auto u = std::stoul(s, nullptr, 10);
assert(u <= UINT16_MAX); assert(u <= UINT16_MAX);
return Signal(static_cast<std::uint16_t>(u)); return {static_cast<std::uint16_t>(u)};
}
else {
return Signal(s);
} }
return {s};
} }
Action act_; ///< Action Action act_{Action::Not}; ///< Action
Wire dest_; ///< Destination wire Wire dest_; ///< Destination wire
Signal src1_, src2_; ///< Source signals Signal src1_, src2_; ///< Source signals
}; };
/// Outputter for an instruction. /// Outputter for an instruction.
std::ostream& operator<<(std::ostream& os, Instruction const& instr) auto operator<<(std::ostream& os, Instruction const& instr) -> std::ostream&
{ {
os << instr.action() << " " << instr.dest() << ", " << instr.src1(); os << instr.action() << " " << instr.dest() << ", " << instr.src1();
if (instr.action() != Action::Set && instr.action() != Action::Not) { if (instr.action() != Action::Set && instr.action() != Action::Not) {
@@ -230,27 +228,30 @@ using Instructions = std::vector<Instruction>; ///< Instructions to execute
struct VM struct VM
{ {
/// Add an instruction the the list we have /// Add an instruction the the list we have
void add_instr(Instruction const& instr) { instrs_.push_back(instr); } void add_instr(Instruction const& instr) { instructions_.push_back(instr); }
/// Has this wire a known value? /// Has this wire a known value?
bool has_value(Wire const& w) const noexcept { return values_.find(w) != values_.end(); } [[nodiscard]] auto has_value(Wire const& w) const noexcept -> bool
{
return values_.find(w) != values_.end();
}
/// Has this signal a known value? /// Has this signal a known value?
bool has_value(Signal const& s) const noexcept [[nodiscard]] auto has_value(Signal const& s) const noexcept -> bool
{ {
return std::visit( return std::visit(
Overloaded{[](Value v) { return true; }, [&](Wire const& w) { return has_value(w); }}, s); Overloaded{[](Value /*v*/) { return true; }, [&](Wire const& w) { return has_value(w); }}, s);
} }
/// Get the value on the wire /// Get the value on the wire
Value value(Wire const& w) const noexcept [[nodiscard]] auto value(Wire const& w) const noexcept -> Value
{ {
assert(has_value(w)); assert(has_value(w));
return values_.find(w)->second; return values_.find(w)->second;
} }
/// Get the value of a signal /// Get the value of a signal
Value value(Signal const& s) const noexcept [[nodiscard]] auto value(Signal const& s) const noexcept -> Value
{ {
return std::visit( return std::visit(
Overloaded{[](Value v) { return v; }, [&](Wire const& w) { return value(w); }}, s); Overloaded{[](Value v) { return v; }, [&](Wire const& w) { return value(w); }}, s);
@@ -267,15 +268,17 @@ struct VM
void value(Signal const& s, Value v) void value(Signal const& s, Value v)
{ {
std::visit( std::visit(
Overloaded{[v](Value v2) { assert(v == v2); }, [&, v](Wire const& w) { value(w, v); }}, s); Overloaded{[v](Value v2) { assert(v == v2); },
[&, v](Wire const& w) { value(w, v); }}, // NOLINT(bugprone-lambda-function-name)
s); // NOLINT(bugprone-lambda-function-name)
} }
/// Execute the instructions. Returns true if we have updated some wire /// Execute the instructions. Returns true if we have updated some wire
/// values. /// values.
bool execute() auto execute() -> bool
{ {
bool done_anything = false; bool done_anything = false;
for (auto const& instr : instrs_) { for (auto const& instr : instructions_) {
done_anything |= execute_instr(instr); done_anything |= execute_instr(instr);
} }
@@ -290,13 +293,13 @@ private:
* An instruction may not be executed if the incoming signals have not been * An instruction may not be executed if the incoming signals have not been
* set yet. * set yet.
*/ */
bool execute_instr(Instruction const& instr) auto execute_instr(Instruction const& instr) -> bool
{ {
std::cout << instr << " # "; std::cout << instr << " # ";
// First of all check there is something to do - i.e. that the destination // First of all check there is something to do - i.e. that the destination
// register has not been set already. // register has not been set already.
Wire dest = instr.dest(); auto const& dest = instr.dest();
if (has_value(dest)) { if (has_value(dest)) {
std::cout << "already has value: " << dest << " = " << value(dest) << "\n"; std::cout << "already has value: " << dest << " = " << value(dest) << "\n";
return false; return false;
@@ -325,10 +328,10 @@ private:
* \param fn How to modify the source value to the dest. * \param fn How to modify the source value to the dest.
* \return True if we executed the function. * \return True if we executed the function.
*/ */
bool execute_single_src(Instruction const& instr, std::function<Value(Value)> fn) auto execute_single_src(Instruction const& instr, const std::function<Value(Value)>& fn) -> bool
{ {
Wire dest = instr.dest(); const Wire& dest = instr.dest();
Signal src = instr.src1(); const Signal& src = instr.src1();
if (has_value(src)) { if (has_value(src)) {
value(dest, fn(value(src))); value(dest, fn(value(src)));
std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n"; std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n";
@@ -344,11 +347,12 @@ private:
* \param fn How to modify the source values to the dest. * \param fn How to modify the source values to the dest.
* \return True if we executed the function. * \return True if we executed the function.
*/ */
bool execute_double_src(Instruction const& instr, std::function<Value(Value, Value)> fn) auto execute_double_src(Instruction const& instr, const std::function<Value(Value, Value)>& fn)
-> bool
{ {
Wire dest = instr.dest(); const Wire& dest = instr.dest();
Signal src1 = instr.src1(); const Signal& src1 = instr.src1();
Signal src2 = instr.src2(); const Signal& src2 = instr.src2();
if (has_value(src1) && has_value(src2)) { if (has_value(src1) && has_value(src2)) {
value(dest, fn(value(src1), value(src2))); value(dest, fn(value(src1), value(src2)));
std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n"; std::cout << "setting wire to: " << dest << " = " << value(dest) << "\n";
@@ -360,10 +364,10 @@ private:
} }
ValueMap values_; ValueMap values_;
Instructions instrs_; Instructions instructions_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
VM vm; VM vm;

View File

@@ -1,14 +1,11 @@
#include <cassert> #include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <string> #include <string>
#include <variant>
enum class State { Begin, Normal, Escape, Hex1, Hex2, End }; enum class State { Begin, Normal, Escape, Hex1, Hex2, End };
std::string unescape(std::string const& s) auto unescape(std::string const& s) -> std::string
{ {
std::string unescaped; std::string unescaped;
static const std::string hex = "0123456789abcdef0123456789ABCDEF"; static const std::string hex = "0123456789abcdef0123456789ABCDEF";
@@ -56,7 +53,7 @@ std::string unescape(std::string const& s)
auto idx = hex.find(c); auto idx = hex.find(c);
assert(idx != std::string::npos); assert(idx != std::string::npos);
byte = (byte << 4) + (idx & 0xf); byte = (byte << 4) + (idx & 0xf);
unescaped += (char)byte; unescaped += static_cast<char>(byte);
state = State::Normal; state = State::Normal;
break; break;
} }
@@ -67,7 +64,7 @@ std::string unescape(std::string const& s)
return unescaped; return unescaped;
} }
int main(int argc, char** argv) auto main() -> int
{ {
unsigned len = 0; unsigned len = 0;

View File

@@ -1,12 +1,7 @@
#include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <string>
#include <variant>
std::string escape(std::string const& s) auto escape(std::string const& s) -> std::string
{ {
std::string escaped; std::string escaped;
escaped += '"'; escaped += '"';
@@ -20,7 +15,7 @@ std::string escape(std::string const& s)
return escaped; return escaped;
} }
int main(int argc, char** argv) auto main() -> int
{ {
unsigned len = 0; unsigned len = 0;

View File

@@ -21,8 +21,7 @@ struct Graph
std::smatch m; std::smatch m;
if (!std::regex_search(s, m, re)) { if (!std::regex_search(s, m, re)) {
std::cout << "Failed to match: " << s << "\n"; std::cout << "Failed to match: " << s << "\n";
assert(false); abort();
return;
} }
auto n1 = m.str(1); auto n1 = m.str(1);
auto n2 = m.str(2); auto n2 = m.str(2);
@@ -37,7 +36,7 @@ struct Graph
std::cout << n1 << " <-> " << n2 << " weight: " << w << "\n"; std::cout << n1 << " <-> " << n2 << " weight: " << w << "\n";
} }
Weight solve_tsp() const [[nodiscard]] auto solve_tsp() const -> Weight
{ {
Weight min_weight = ~0U; Weight min_weight = ~0U;
std::vector<Node> nodes(nodes_.begin(), nodes_.end()); std::vector<Node> nodes(nodes_.begin(), nodes_.end());
@@ -67,7 +66,7 @@ struct Graph
Edges weights_; Edges weights_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
Graph g; Graph g;

View File

@@ -21,8 +21,7 @@ struct Graph
std::smatch m; std::smatch m;
if (!std::regex_search(s, m, re)) { if (!std::regex_search(s, m, re)) {
std::cout << "Failed to match: " << s << "\n"; std::cout << "Failed to match: " << s << "\n";
assert(false); abort();
return;
} }
auto n1 = m.str(1); auto n1 = m.str(1);
auto n2 = m.str(2); auto n2 = m.str(2);
@@ -37,7 +36,7 @@ struct Graph
std::cout << n1 << " <-> " << n2 << " weight: " << w << "\n"; std::cout << n1 << " <-> " << n2 << " weight: " << w << "\n";
} }
Weight solve_tsp() const [[nodiscard]] auto solve_tsp() const -> Weight
{ {
Weight min_weight = ~0U; Weight min_weight = ~0U;
visit_all_perms([&min_weight](Weight w) { visit_all_perms([&min_weight](Weight w) {
@@ -49,7 +48,7 @@ struct Graph
return min_weight; return min_weight;
} }
Weight solve_max_tsp() const [[nodiscard]] auto solve_max_tsp() const -> Weight
{ {
Weight max_weight = 0; Weight max_weight = 0;
visit_all_perms([&max_weight](Weight w) { visit_all_perms([&max_weight](Weight w) {
@@ -86,7 +85,7 @@ private:
Edges weights_; Edges weights_;
}; };
int main(int argc, char** argv) auto main() -> int
{ {
Graph g; Graph g;

View File

@@ -1,13 +1,8 @@
#include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
std::string look_and_say(std::string const& s) auto look_and_say(std::string const& s) -> std::string
{ {
std::string result; std::string result;
for (std::string::size_type i = 0; i < s.length();) { for (std::string::size_type i = 0; i < s.length();) {
@@ -23,7 +18,7 @@ std::string look_and_say(std::string const& s)
return result; return result;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::cout << "Application 0, length = " << line.length() << ": " << line << "\n"; std::cout << "Application 0, length = " << line.length() << ": " << line << "\n";

View File

@@ -1,13 +1,8 @@
#include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
std::string look_and_say(std::string const& s) auto look_and_say(std::string const& s) -> std::string
{ {
std::string result; std::string result;
for (std::string::size_type i = 0; i < s.length();) { for (std::string::size_type i = 0; i < s.length();) {
@@ -23,7 +18,7 @@ std::string look_and_say(std::string const& s)
return result; return result;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::cout << "Application 0, length = " << line.length() << ": " << line << "\n"; std::cout << "Application 0, length = " << line.length() << ": " << line << "\n";

View File

@@ -1,13 +1,9 @@
#include <cassert> #include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
bool illegal_char(char c) { return c == 'i' || c == 'l' || c == 'o'; } auto illegal_char(char c) -> bool { return c == 'i' || c == 'l' || c == 'o'; }
void pre_advance_password(std::string& s) void pre_advance_password(std::string& s)
{ {
@@ -43,7 +39,7 @@ void advance_password(std::string& s)
} }
} }
bool valid_password(std::string const& s) auto valid_password(std::string const& s) -> bool
{ {
unsigned double_count = 0; unsigned double_count = 0;
bool run = false; bool run = false;
@@ -63,7 +59,7 @@ bool valid_password(std::string const& s)
return double_count >= 2 && run; return double_count >= 2 && run;
} }
std::string next_password(std::string const& s) auto next_password(std::string const& s) -> std::string
{ {
std::string result = s; std::string result = s;
pre_advance_password(result); pre_advance_password(result);
@@ -73,7 +69,7 @@ std::string next_password(std::string const& s)
return result; return result;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::string next = next_password(line); std::string next = next_password(line);

View File

@@ -1,13 +1,9 @@
#include <cassert> #include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
bool illegal_char(char c) { return c == 'i' || c == 'l' || c == 'o'; } auto illegal_char(char c) -> bool { return c == 'i' || c == 'l' || c == 'o'; }
void pre_advance_password(std::string& s) void pre_advance_password(std::string& s)
{ {
@@ -43,7 +39,7 @@ void advance_password(std::string& s)
} }
} }
bool valid_password(std::string const& s) auto valid_password(std::string const& s) -> bool
{ {
unsigned double_count = 0; unsigned double_count = 0;
bool run = false; bool run = false;
@@ -63,7 +59,7 @@ bool valid_password(std::string const& s)
return double_count >= 2 && run; return double_count >= 2 && run;
} }
std::string next_password(std::string const& s) auto next_password(std::string const& s) -> std::string
{ {
std::string result = s; std::string result = s;
pre_advance_password(result); pre_advance_password(result);
@@ -73,7 +69,7 @@ std::string next_password(std::string const& s)
return result; return result;
} }
int main(int argc, char** argv) auto main() -> int
{ {
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {
std::string next = next_password(line); std::string next = next_password(line);

View File

@@ -1,13 +1,9 @@
#include <cassert>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex> #include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
int parse_numbers(std::string const& s) auto parse_numbers(std::string const& s) -> int
{ {
static const std::regex re("-?\\d+"); static const std::regex re("-?\\d+");
std::string left = s; std::string left = s;
@@ -21,7 +17,7 @@ int parse_numbers(std::string const& s)
return acc; return acc;
} }
int main(int argc, char** argv) auto main() -> int
{ {
int acc = 0; int acc = 0;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {

View File

@@ -2,23 +2,15 @@
#include <cctype> #include <cctype>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string> #include <string>
#include <variant>
int do_parse(std::string const& s, std::string::size_type& pos) auto do_parse(std::string const& s, std::string::size_type& pos) -> int
{ {
int result = 0; int result = 0;
bool ignore = false; bool ignore = false;
while (pos < s.size()) { while (pos < s.size()) {
if (s[pos] == '{') { if (s[pos] == '{' || s[pos] == '[') {
++pos;
result += do_parse(s, pos);
}
else if (s[pos] == '[') {
++pos; ++pos;
result += do_parse(s, pos); result += do_parse(s, pos);
} }
@@ -40,7 +32,7 @@ int do_parse(std::string const& s, std::string::size_type& pos)
} }
pos = e + 1; pos = e + 1;
} }
else if (std::isdigit(s[pos]) || s[pos] == '-') { else if (std::isdigit(s[pos]) == 1 || s[pos] == '-') {
std::size_t len = 0; std::size_t len = 0;
result += std::stoi(s.substr(pos), &len); result += std::stoi(s.substr(pos), &len);
pos += len; pos += len;
@@ -54,7 +46,7 @@ int do_parse(std::string const& s, std::string::size_type& pos)
return result; return result;
} }
int parse_numbers(std::string const& s) auto parse_numbers(std::string const& s) -> int
{ {
std::string::size_type pos = 0; std::string::size_type pos = 0;
int result = do_parse(s, pos); int result = do_parse(s, pos);
@@ -62,7 +54,7 @@ int parse_numbers(std::string const& s)
return result; return result;
} }
int main(int argc, char** argv) auto main() -> int
{ {
int acc = 0; int acc = 0;
for (std::string line; std::getline(std::cin, line);) { for (std::string line; std::getline(std::cin, line);) {

View File

@@ -89,16 +89,16 @@ struct VM
void add_instruction(Instruction const& i) void add_instruction(Instruction const& i)
{ {
std::cout << i << "\n"; std::cout << i << "\n";
instrs_.push_back(i); instructions_.push_back(i);
} }
void execute() void execute()
{ {
std::vector<bool> seen(instrs_.size(), false); std::vector<bool> seen(instructions_.size(), false);
while (!seen[pc_]) { while (!seen[pc_]) {
assert(pc_ < instrs_.size()); assert(pc_ < instructions_.size());
seen[pc_] = true; seen[pc_] = true;
execute(instrs_[pc_]); execute(instructions_[pc_]);
++pc_; ++pc_;
} }
std::cout << "PC seen before: " << pc_ << "\n"; std::cout << "PC seen before: " << pc_ << "\n";
@@ -127,7 +127,7 @@ private:
std::cout << "\n"; std::cout << "\n";
} }
Instructions instrs_; Instructions instructions_;
std::size_t pc_; std::size_t pc_;
Value acc_; Value acc_;
}; };

View File

@@ -104,20 +104,20 @@ struct VM
void add_instruction(Instruction const& i) void add_instruction(Instruction const& i)
{ {
std::cout << i << "\n"; std::cout << i << "\n";
instrs_.push_back(i); instructions_.push_back(i);
} }
bool execute() bool execute()
{ {
std::vector<bool> seen(instrs_.size(), false); std::vector<bool> seen(instructions_.size(), false);
acc_ = 0; acc_ = 0;
pc_ = 0; pc_ = 0;
while (!seen[pc_]) { while (!seen[pc_]) {
assert(pc_ < instrs_.size()); assert(pc_ < instructions_.size());
seen[pc_] = true; seen[pc_] = true;
execute(instrs_[pc_]); execute(instructions_[pc_]);
++pc_; ++pc_;
if (pc_ == instrs_.size()) { if (pc_ == instructions_.size()) {
std::cout << "Terminated\n"; std::cout << "Terminated\n";
return true; return true;
} }
@@ -128,13 +128,13 @@ struct VM
void find_fix() void find_fix()
{ {
for (std::size_t pos = 0; pos < instrs_.size(); ++pos) { for (std::size_t pos = 0; pos < instructions_.size(); ++pos) {
if (instrs_[pos].flip_jmp()) { if (instructions_[pos].flip_jmp()) {
if (execute()) { if (execute()) {
std::cout << "Success at instruction " << pos << ": " << instrs_[pos] << "\n"; std::cout << "Success at instruction " << pos << ": " << instructions_[pos] << "\n";
return; return;
} }
instrs_[pos].flip_jmp(); instructions_[pos].flip_jmp();
} }
} }
} }
@@ -162,7 +162,7 @@ private:
std::cout << "\n"; std::cout << "\n";
} }
Instructions instrs_; Instructions instructions_;
std::size_t pc_; std::size_t pc_;
Value acc_; Value acc_;
}; };