diff --git a/2017/puzzle-03-01.cc b/2017/puzzle-03-01.cc new file mode 100644 index 0000000..7ac9d42 --- /dev/null +++ b/2017/puzzle-03-01.cc @@ -0,0 +1,46 @@ +#include +#include + +template +auto sign(T i) -> decltype(i) +{ + if (i < 0) { + return -1; + } + if (i > 0) { + return 1; + } + return 0; +} + +auto main() -> int +{ + std::string line; + if (!std::getline(std::cin, line)) { + std::cerr << "Broken line" << '\n'; + return 1; + } + + auto target{std::stoul(line)}; + std::pair dist{1, 0}; + std::pair pos{0, 0}; + decltype(target) val{1}; + + while (val + std::abs(dist.first) + std::abs(dist.second) < target) { + val += std::abs(dist.first) + std::abs(dist.second); + pos = {pos.first + dist.first, pos.second + dist.second}; + dist = {-dist.second, dist.first}; + if (dist.first > 0) { + ++dist.first; + } + if (dist.first < 0) { + --dist.first; + } + } + auto delta{target - val}; + pos = {pos.first + sign(dist.first) * delta, pos.second + sign(dist.second) * delta}; + + std::cout << "Pos = [" << pos.first << ", " << pos.second + << "], distance = " << std::abs(pos.first) + std::abs(pos.second) << '\n'; + return 0; +} diff --git a/2017/puzzle-03-02.cc b/2017/puzzle-03-02.cc new file mode 100644 index 0000000..a9a5a03 --- /dev/null +++ b/2017/puzzle-03-02.cc @@ -0,0 +1,71 @@ +#include +#include +#include + +using Int = long; +using Coord = std::pair; +using ValueMap = std::map; + +template +auto sign(T i) -> decltype(i) +{ + if (i < 0) { + return -1; + } + if (i > 0) { + return 1; + } + return 0; +} + +auto value(ValueMap const& map, Coord const& coord) -> Int +{ + auto result{0}; + for (auto x{coord.first - 1}; x < coord.first + 2; ++x) { + for (auto y{coord.second - 1}; y < coord.second + 2; ++y) { + if (x == coord.first && y == coord.second) { + continue; + } + auto it{map.find(Coord{x, y})}; + if (it != map.end()) { + result += it->second; + } + } + } + + return result; +} + +auto main() -> int +{ + std::string line; + if (!std::getline(std::cin, line)) { + std::cerr << "Broken line" << '\n'; + return 1; + } + + auto target{std::stol(line)}; + Coord dir{1, 0}; + Coord pos{0, 0}; + Int count{1}; + Int count_reset{1}; + ValueMap map; + map.insert({pos, 1}); + + while (true) { + while (count-- != 0) { + pos = {pos.first + dir.first, pos.second + dir.second}; + auto val{value(map, pos)}; + if (val > target) { + std::cout << val << '\n'; + return 0; + } + map.insert({pos, val}); + } + dir = {-dir.second, dir.first}; + if (dir.first != 0) { + ++count_reset; + } + count = count_reset; + } +}