Playing with C++17 via solving "Cracking the Coding Interview" questions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cxx17/cc18.cc

83 lines
1.5 KiB

// If a cell is zero, the row and column are set to zero.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <fmt/format.h>
#include <experimental/string_view>
#include <string>
#include <unordered_set>
using string_view = std::experimental::string_view;
using matrix = std::array<std::array<char, 4>, 3>;
template <typename T>
std::string to_string(const T& img) {
std::string out;
for (const auto& row : img) {
for (auto ch : row) {
out.push_back(ch);
}
out.push_back(';');
}
return out;
}
void fill(matrix& m) {
for (auto& row : m) {
for (auto& ch : row) {
ch = '1';
}
}
}
void clear(matrix& m) {
// Record the rows and cols that have a zero in them.
std::unordered_set<size_t> rows;
std::unordered_set<size_t> cols;
for (size_t y = 0; y < m.size(); y++) {
auto& row = m[y];
for (size_t x = 0; x < row.size(); x++) {
if (row[x] == '0') {
cols.insert(x);
rows.insert(y);
}
}
}
// Now go and clear the rows and cols.
for (auto y : rows) {
for (auto& ch : m[y]) {
ch = '0';
}
}
for (auto x : cols) {
for (auto& row : m) {
row[x] = '0';
}
}
}
TEST_CASE("cc18", "zeros") {
matrix m;
fill(m);
CHECK(to_string(m) == "1111;1111;1111;");
m[0][1] = '0';
CHECK(to_string(m) == "1011;1111;1111;");
clear(m);
CHECK(to_string(m) == "0000;1011;1011;");
fill(m);
m[0][0] = '0';
m[2][3] = '0';
clear(m);
CHECK(to_string(m) == "0000;0110;0000;");
}