ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Robot Command Simulator

Move a robot using L (turn left 90 degrees), R (turn right 90 degrees), and A (advance one step).

สิ่งที่คุณจะได้เรียนรู้

  • ติดตามตำแหน่งและทิศที่หันหน้า
  • เลี้ยวซ้ายและขวาด้วยอาร์เรย์ทิศทาง
  • ประมวลผลสตริงคำสั่งทีละขั้น

โจทย์

Move a robot using L (turn left 90 degrees), R (turn right 90 degrees), and A (advance one step). Turning does not move it. Positive x points east and positive y points north. Directions are encoded as 0 = north, 1 = east, 2 = south, 3 = west. There are no obstacles or boundaries.

Implement robot_command_simulator(x, y, direction, commands).

Input

x: Initial horizontal coordinate.

y: Initial vertical coordinate.

direction: Initial direction: 0 north, 1 east, 2 south, 3 west.

commands: Commands to process from left to right.

Output

Return [final_x, final_y, final_direction], using the same direction encoding.

เงื่อนไข

−1,000,000,000 ≤ initial x, y ≤ 1,000,000,000. Direction is 0…3. There are 0…100,000 commands, each uppercase L, R, or A.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
x = 0
y = 0
direction = 0
commands = "RAALA"

ผลลัพธ์ที่คาดหวัง:
expected = [2, 1, 0]
อินพุต:
long long x = 0;
long long y = 0;
long long direction = 0;
std::string commands = "RAALA";

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {2, 1, 0};
อินพุต:
long x = 0;
long y = 0;
long direction = 0;
string commands = "RAALA";

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {2, 1, 0};

คำอธิบาย

Turn east, advance twice to (2, 0), turn north, then advance to (2, 1). Direction 0 means north.

ตัวอย่างที่ 2
อินพุต:
x = 3
y = -2
direction = 1
commands = "LLLL"

ผลลัพธ์ที่คาดหวัง:
expected = [3, -2, 1]
อินพุต:
long long x = 3;
long long y = -2;
long long direction = 1;
std::string commands = "LLLL";

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {3, -2, 1};
อินพุต:
long x = 3;
long y = -2;
long direction = 1;
string commands = "LLLL";

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {3, -2, 1};

คำอธิบาย

Four left turns restore the original east-facing direction (1). Turning never changes the coordinates.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

ติดตามตำแหน่งและทิศทางแยกกัน; คำสั่งหมุนเปลี่ยนทิศโดยไม่ขยับหุ่นยนต์

คำใบ้ 2

คำสั่ง advance ใช้ทิศปัจจุบันเพื่อปรับพิกัดหนึ่งแกนทีละ 1 ก้าว

คำใบ้ 3

อย่าลืมว่าทิศจะวนรอบเมื่อเลี้ยวซ้ายจาก north หรือเลี้ยวขวาจาก west

ความซับซ้อนที่คาดหวัง

เวลา O(n), หน่วยความจำเพิ่ม O(1)

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก