{ }codelper
enumsswitchP0077

Which way the turtle faces

A turtle stands at (0, 0) facing north.
One step north increases y by 1, east increases x by 1, south decreases y by 1, and west decreases x by 1.
One line gives the command letters with no spaces.
F moves one step in the facing direction, R turns 90 degrees right, L turns 90 degrees left, and B turns around in place (180 degrees).
After all the commands, print the turtle's x, y and the first letter of its facing direction (one of N, E, S, W), separated by single spaces.
Try modeling the direction as an enum with the four values north, east, south, west in clockwise order.

Input
The command is 1 to 100,000 letters long, each one of F, R, L, B
Output
One line: x y direction
Example 1 · stdin
FFRFFLFBFF
stdout
2 1 S
Example 2 · stdin
LF
stdout
-1 0 W
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 6 languages

This problem accepts only the languages where it can be solved with an enum: Python, TypeScript, Java, C#, C and C++.
Python builds one with class Dir(Enum) from the standard enum module.
JavaScript has no enum syntax (you can only imitate one with Object.freeze({...})), so it is left out, and Craykon has no enums either.
TypeScript's enum Dir { North, East, South, West } is a numeric enum with the values 0 to 3, so you compute with numbers as in (d + 1) % 4 and turn the result back with as Dir, and the reverse mapping Dir[d] gives the name "North".
An enum is not type-only syntax: it produces an object that is used at run time.
What an enum is differs by language.
C's enum Dir { NORTH, EAST, SOUTH, WEST } is just named int constants 0 to 3, so the names are unknown at run time and you keep a label table such as "NESW"[d].
C++ enum class is written Dir::North and does not convert to int by itself, so you need static_cast<int>(d).
A Java enum is a class with values(), ordinal() and name(); C# converts with (Dir)(((int)d + 1) % 4) and d.ToString() gives the name.
Python has Dir(value), d.value and d.name.
Three traps: (1) writing a left turn as (d - 1) % 4 gives -1 from north (0) in C, C++, Java, C# and TypeScript, because the remainder takes the sign of the dividend; C# even builds (Dir)(-1) without error and prints "-1", and TypeScript does not stop -1 as Dir either, so Dir[-1] is undefined.
Use (d + 3) % 4 (Python is fine since -1 % 4 == 3).
(2) In C and C++ (and Java's old case: switch), a missing break falls through to the next case, moving several times in one step.
C# rejects this at compile time, and Java's arrow switch case NORTH -> y++; never falls through.
(3) A Python Enum member is not equal to a number, so d == 0 is always False (it would be True with IntEnum); compare with d == Dir.NORTH or d.value.

Pythonmain.py · 23 lines
from enum import Enum  class Dir(Enum):  # 시계 방향 차례    NORTH = 0    EAST = 1    SOUTH = 2    WEST = 3  STEP = {Dir.NORTH: (0, 1), Dir.EAST: (1, 0), Dir.SOUTH: (0, -1), Dir.WEST: (-1, 0)}TURN = {"R": 1, "B": 2, "L": 3}  # 왼쪽 = 오른쪽으로 세 번 x = y = 0d = Dir.NORTHfor c in input().strip():    if c == "F":        dx, dy = STEP[d]        x += dx        y += dy    else:        d = Dir((d.value + TURN[c]) % 4)  # 수로 바꿔 계산하고 다시 열거형으로print(x, y, d.name[0])
TypeScriptmain.ts · 34 lines
import { readFileSync } from "node:fs"; enum Dir { // 시계 방향 차례: North = 0, East = 1, South = 2, West = 3  North,  East,  South,  West,} // 숫자 enum은 수로 계산할 수 있다. 결과를 다시 Dir로 돌려놓는다function turn(d: Dir, k: number): Dir {  return ((d + k) % 4) as Dir; // 왼쪽은 -1 대신 +3} const s = readFileSync(0, "utf8").trim();let x = 0;let y = 0;let d = Dir.North;for (const c of s) {  switch (c) {    case "R": d = turn(d, 1); break;    case "B": d = turn(d, 2); break;    case "L": d = turn(d, 3); break;    default:      switch (d) {        case Dir.North: y++; break;        case Dir.East: x++; break;        case Dir.South: y--; break;        case Dir.West: x--; break;      }  }}// 역방향 표 Dir[d]가 이름("South")을 준다console.log(`${x} ${y} ${Dir[d].charAt(0)}`);
JavaMain.java · 33 lines
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    enum Dir { NORTH, EAST, SOUTH, WEST } // 시계 방향 차례     static Dir turn(Dir d, int k) {        Dir[] all = Dir.values();        return all[(d.ordinal() + k) % 4];    }     public static void main(String[] args) throws Exception {        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();        int x = 0, y = 0;        Dir d = Dir.NORTH;        for (char c : s.toCharArray()) {            switch (c) {                case 'R' -> d = turn(d, 1);                case 'B' -> d = turn(d, 2);                case 'L' -> d = turn(d, 3);                default -> {                    switch (d) { // 화살표 switch는 아래로 흘러내리지 않는다                        case NORTH -> y++;                        case EAST -> x++;                        case SOUTH -> y--;                        case WEST -> x--;                    }                }            }        }        System.out.println(x + " " + y + " " + d.name().charAt(0));    }}
C#Main.cs · 34 lines
using System; enum Dir { North, East, South, West } // 시계 방향 차례 class Program{    static Dir Turn(Dir d, int k) => (Dir)(((int)d + k) % 4); // 열거형 ↔ int는 명시적으로 바꾼다     static void Main()    {        string s = Console.ReadLine().Trim();        int x = 0, y = 0;        Dir d = Dir.North;        foreach (char c in s)        {            switch (c)            {                case 'R': d = Turn(d, 1); break;                case 'B': d = Turn(d, 2); break;                case 'L': d = Turn(d, 3); break;                default:                    switch (d)                    {                        case Dir.North: y++; break;                        case Dir.East: x++; break;                        case Dir.South: y--; break;                        case Dir.West: x--; break;                    }                    break;            }        }        Console.WriteLine($"{x} {y} {d.ToString()[0]}");    }}
C++main.cpp · 34 lines
#include <iostream>#include <string> enum class Dir { North, East, South, West };  // 범위 있는 열거형: Dir::North로 쓰고 int로 저절로 바뀌지 않는다 Dir turn(Dir d, int k) {    return static_cast<Dir>((static_cast<int>(d) + k) % 4);} char name(Dir d) {    return "NESW"[static_cast<int>(d)];  // C++도 열거형의 이름을 실행 중에 모른다} int main() {    std::string s;    std::cin >> s;    int x = 0, y = 0;    Dir d = Dir::North;    for (char c : s) {        switch (c) {        case 'R': d = turn(d, 1); break;        case 'B': d = turn(d, 2); break;        case 'L': d = turn(d, 3); break;        default:            switch (d) {            case Dir::North: y++; break;            case Dir::East:  x++; break;            case Dir::South: y--; break;            case Dir::West:  x--; break;            }        }    }    std::cout << x << " " << y << " " << name(d) << "\n";}
Cmain.c · 32 lines
#include <stdio.h> enum Dir { NORTH, EAST, SOUTH, WEST };  /* 이름 붙은 int 상수 0, 1, 2, 3 */ static const char NAME[] = "NESW";      /* C 열거형은 실행 중에 이름을 모른다: 직접 둔다 */ enum Dir turn(enum Dir d, int k) {    return (enum Dir)((d + k) % 4);} int main(void) {    static char s[100002];    scanf("%100001s", s);    int x = 0, y = 0;    enum Dir d = NORTH;    for (int i = 0; s[i]; i++) {        switch (s[i]) {        case 'R': d = turn(d, 1); break;        case 'B': d = turn(d, 2); break;        case 'L': d = turn(d, 3); break;        default:            switch (d) {            case NORTH: y++; break;  /* break가 없으면 다음 case로 흘러내린다 */            case EAST:  x++; break;            case SOUTH: y--; break;            case WEST:  x--; break;            }        }    }    printf("%d %d %c\n", x, y, NAME[d]);    return 0;}