cc18: added a solution.

master
Michael Hope 6 years ago
parent 68e11c990b
commit 23f8be7315
  1. 4
      CMakeLists.txt
  2. 83
      cc18.cc

@ -41,3 +41,7 @@ add_test(cc16 bin/cc16)
add_executable(cc17 cc17.cc)
target_link_libraries(cc17 ${CONAN_LIBS})
add_test(cc17 bin/cc17)
add_executable(cc18 cc18.cc)
target_link_libraries(cc18 ${CONAN_LIBS})
add_test(cc18 bin/cc18)

@ -0,0 +1,83 @@
// 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;");
}
Loading…
Cancel
Save