Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "copter.h"
- #include <sstream>
- #include <exception>
- #include <cstring>
- void
- CopterState::dump_mem(std::ostream &out) const
- {
- for (int i = 0; i < MEMORY_SIZE; ++i) {
- if (i > 0) out << ' ';
- out << int(mem_[i]);
- }
- out << std::endl;
- }
- CopterState::Direction
- CopterState::neighbour_kind(const CopterState &other) const noexcept
- {
- if (x_ == other.x_ && y_ == other.y_) {
- return Direction::SAME;
- } else if (x_ == other.x_ + 1 && y_ == other.y_) {
- return Direction::LEFT;
- } else if (x_ == other.x_ - 1 && y_ == other.y_) {
- return Direction::RIGHT;
- } else if (x_ == other.x_ && y_ == other.y_ - 1) {
- return Direction::UP;
- } else if (x_ == other.x_ && y_ == other.y_ + 1) {
- return Direction::DOWN;
- }
- return Direction::AWAY;
- }
- void
- CopterState::parse_copter_output(int x, int y, std::string &str)
- {
- std::istringstream ss(str);
- int dest = 0;
- ss >> dest;
- if (!ss || dest <= 0 || dest > int(CopterState::Direction::SAME)) {
- throw std::invalid_argument(std::string("invalid destination ") + std::to_string(dest));
- }
- unsigned char mem[MEMORY_SIZE] = {};
- for (int i = 0; i < MEMORY_SIZE; ++i) {
- int val;
- ss >> val;
- if (!ss) {
- throw std::invalid_argument(std::string("failed to read memory value ") + "[" + std::to_string(i) + "]");
- }
- if (val < 0 || val > 255) {
- throw std::invalid_argument(std::string("invalid memory value ") + "[" + std::to_string(i) + "]: " + std::to_string(val));
- }
- mem[i] = val;
- }
- // check for garbage
- switch (dest) {
- case 1: // left
- x_ = x - 1;
- y_ = y;
- break;
- case 2: // right
- x_ = x + 1;
- y_ = y;
- break;
- case 3: // up
- x_ = x;
- y_ = y + 1;
- break;
- case 4: // down
- x_ = x;
- y_ = y - 1;
- break;
- case 5: // stay put
- x_ = x;
- y_ = y;
- break;
- default:
- throw std::invalid_argument(std::string("invalid destination ") + std::to_string(dest));
- }
- memcpy(mem_, mem, sizeof(mem_));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement