cc17: add a solution.

master
Michael Hope 6 years ago
parent 90529ae14f
commit 68e11c990b
  1. 4
      CMakeLists.txt
  2. 73
      cc17.cc

@ -37,3 +37,7 @@ add_executable(cc16 cc16.cc)
target_link_libraries(cc16 ${CONAN_LIBS})
add_test(cc16 bin/cc16)
# set_property(TARGET cc16 PROPERTY CXX_INCLUDE_WHAT_YOU_USE ${iwyu_path})
add_executable(cc17 cc17.cc)
target_link_libraries(cc17 ${CONAN_LIBS})
add_test(cc17 bin/cc17)

@ -0,0 +1,73 @@
// Rotate a square matrix in place.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <fmt/format.h>
#include <experimental/string_view>
#include <string>
using string_view = std::experimental::string_view;
using image = std::array<std::array<uint32_t, 3>, 3>;
image parse(string_view in) {
image out;
size_t x = 0;
size_t y = 0;
for (auto ch : in) {
if (ch == ';') {
continue;
}
out[y][x] = ch;
if (++x == out[0].size()) {
y++;
x = 0;
}
}
return out;
}
std::string to_string(const image& img) {
std::string out;
for (const auto& row : img) {
for (auto ch : row) {
out.push_back(char(ch));
}
out.push_back(';');
}
return out;
}
image rotate(image in) {
// TODO(michaelh): image is heavy but there's no temporary to pass
// about.
image out;
// TODO(michaelh): the problem says in-place. I think you can using
// one temporary value so, for example, the flow is:
//
// c -> tmp
// a -> c'
// h -> a'
// j -> h'
// tmp -> j'
//
for (size_t y = 0; y < in.size(); y++) {
for (size_t x = 0; x < in[0].size(); x++) {
out[x][in.size() - y - 1] = in[y][x];
}
}
return out;
}
TEST_CASE("cc17", "compress") {
// abc hda
// def --> ieb
// hij jfc
CHECK(to_string(rotate(parse("abcdefhij"))) == "hda;ieb;jfc;");
}
Loading…
Cancel
Save