cxx17/cc17.cc

74 lines
1.3 KiB
C++

// 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;");
}