Advertisement
Guest User

Untitled

a guest
Dec 13th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. #include "copter.h"
  2.  
  3. #include <sstream>
  4. #include <exception>
  5. #include <cstring>
  6.  
  7. void
  8. CopterState::dump_mem(std::ostream &out) const
  9. {
  10. for (int i = 0; i < MEMORY_SIZE; ++i) {
  11. if (i > 0) out << ' ';
  12. out << int(mem_[i]);
  13. }
  14. out << std::endl;
  15. }
  16.  
  17. CopterState::Direction
  18. CopterState::neighbour_kind(const CopterState &other) const noexcept
  19. {
  20. if (x_ == other.x_ && y_ == other.y_) {
  21. return Direction::SAME;
  22. } else if (x_ == other.x_ + 1 && y_ == other.y_) {
  23. return Direction::LEFT;
  24. } else if (x_ == other.x_ - 1 && y_ == other.y_) {
  25. return Direction::RIGHT;
  26. } else if (x_ == other.x_ && y_ == other.y_ - 1) {
  27. return Direction::UP;
  28. } else if (x_ == other.x_ && y_ == other.y_ + 1) {
  29. return Direction::DOWN;
  30. }
  31. return Direction::AWAY;
  32. }
  33.  
  34. void
  35. CopterState::parse_copter_output(int x, int y, std::string &str)
  36. {
  37. std::istringstream ss(str);
  38. int dest = 0;
  39. ss >> dest;
  40. if (!ss || dest <= 0 || dest > int(CopterState::Direction::SAME)) {
  41. throw std::invalid_argument(std::string("invalid destination ") + std::to_string(dest));
  42. }
  43. unsigned char mem[MEMORY_SIZE] = {};
  44. for (int i = 0; i < MEMORY_SIZE; ++i) {
  45. int val;
  46. ss >> val;
  47. if (!ss) {
  48. throw std::invalid_argument(std::string("failed to read memory value ") + "[" + std::to_string(i) + "]");
  49. }
  50. if (val < 0 || val > 255) {
  51. throw std::invalid_argument(std::string("invalid memory value ") + "[" + std::to_string(i) + "]: " + std::to_string(val));
  52. }
  53. mem[i] = val;
  54. }
  55. // check for garbage
  56. switch (dest) {
  57. case 1: // left
  58. x_ = x - 1;
  59. y_ = y;
  60. break;
  61. case 2: // right
  62. x_ = x + 1;
  63. y_ = y;
  64. break;
  65. case 3: // up
  66. x_ = x;
  67. y_ = y + 1;
  68. break;
  69. case 4: // down
  70. x_ = x;
  71. y_ = y - 1;
  72. break;
  73. case 5: // stay put
  74. x_ = x;
  75. y_ = y;
  76. break;
  77. default:
  78. throw std::invalid_argument(std::string("invalid destination ") + std::to_string(dest));
  79. }
  80. memcpy(mem_, mem, sizeof(mem_));
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement