Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาทิศทางจาก String ของ L และ R ใน C++


โจทย์: String ประกอบด้วย 'L' (ซ้าย) และ 'R' (ขวา) เริ่มหันหน้าทิศเหนือ (N) หาทิศทางสุดท้าย

ตัวอย่าง: "RRLRLLR" → E

  • เริ่ม N
  • RR → หันขวา 2 ครั้ง = S
  • LR → หันซ้ายขวา = กลับ N
  • LL → หันซ้ายซ้าย = W? (wait) จริงๆ จาก N: L=W, L=S → S
  • R → หันขวา = W? จริงๆ จาก S: R=W → W

อธิบายในโจทย์: RR→S, LR→N, LL→N (??), R→E → ผล E

อัลกอริธึม

  1. นับ net rotation: R=+1, L=-1
  2. count % 4:
    • >=0: 0→N, 1→E, 2→S, 3→W
    • <0: 0→N, -1→W, -2→S, -3→E

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

string get_dir(string s) {
    int count = 0;
    for (char c : s) {
        if (c == 'L') count--;
        else count++;
    }
    string dir;
    if (count >= 0) {
        switch (count % 4) {
            case 0: dir = "N"; break;
            case 1: dir = "E"; break;
            case 2: dir = "S"; break;
            case 3: dir = "W"; break;
        }
    } else {
        switch (count % 4) {
            case 0: dir = "N"; break;
            case -1: dir = "W"; break;
            case -2: dir = "S"; break;
            case -3: dir = "E"; break;
        }
    }
    return dir;
}

int main() {
    string s = "RRLRLLR";
    cout << get_dir(s); // E
}

อินพุต

"RRLRLLR"

เอาต์พุท

E