處理座標移動指令

嚴正聲明:本文系作者davidhopper原創,未經許可,不得轉載。

題目描述

開發一個座標計算工具, A表示向左移動,D表示向右移動,W表示向上移動,S表示向下移動。從(0,0)點開始移動,從輸入字符串裏面讀取一些座標,並將最終輸入結果輸出到輸出文件裏面。

輸入

合法座標爲A(或者D或者W或者S) + 數字(兩位以內)
座標之間以;分隔。
非法座標點需要進行丟棄。如AA10; A1A; %; YAD; 等。

下面是一個簡單的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;

處理過程:

起點(0,0)

  • A10 = (-10,0)
  • S20 = (-10,-20)
  • W10 = (-10,-10)
  • D30 = (20,-10)
  • x = 無效
  • A1A = 無效
  • B10A11 = 無效
  • 一個空 不影響
  • A10 = (10,-10)
  • 結果 (10, -10)

輸入描述

一行字符串

輸出描述

最終座標,以,分隔

示例1

輸入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

輸出

10,-10

答案

#include <iostream>
#include <string>
#include <vector>

int main() {
  std::string line;
  while (std::getline(std::cin, line)) {
    std::vector<std::string> orders;
    auto pos = line.find(';');
    while (std::string::npos != pos) {
      orders.emplace_back(line.substr(0, pos));
      line.erase(0, pos + 1);
      pos = line.find(';');
    }

    int x = 0;
    int y = 0;

    for (const auto& order : orders) {
      if (order.empty()) {
        continue;
      }
      std::string shift_str = order.substr(1);
      if (shift_str.empty() || shift_str.length() > 2) {
        continue;
      }

      bool invalid = false;
      int shift = 0;
      for (int i = 0; i < shift_str.length(); ++i) {
        char ch = shift_str[i];
        if (ch >= '0' && ch <= '9') {
          shift = shift * 10 + (ch - '0');
        } else {
          invalid = true;
          break;
        }
      }
      if (invalid) {
        continue;
      }

      switch (std::toupper(order[0])) {
        case 'A':
          x -= shift;
          break;

        case 'D':
          x += shift;
          break;

        case 'W':
          y += shift;
          break;

        case 'S':
          y -= shift;
          break;

        default:
          break;
      }
    }

    std::cout << x << "," << y << std::endl;
  }

  return 0;
}

說明

在線測試系統的輸入檢測很弱智,一定要使用類似於while (std::getline(std::cin, line))的循環來檢查輸入數據,否則總是無法通過用例測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章