题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
rl.on("line", function (line) {
    const tokens = line.split(" ");
    const raw = tokens[0];
    const list = raw.split(";");
    let x = 0;
    let y = 0;
    for (let moveInfoRaw of list) {
        const moveInfo = getMoveInfo(moveInfoRaw);
        // console.log({ moveInfo });
        if (moveInfo === "invalid") continue;
        const { direction, value } = moveInfo;
        switch (direction) {
            case "up":
                y += value;
                break;
            case "down":
                y -= value;
                break;
            case "left":
                x -= value;
                break;
            case "right":
                x += value;
                break;
            default:
                continue;
                break;
        }
    }
    console.log(`${x},${y}`);
});

const directionMap = {
    A: "left",
    D: "right",
    W: "up",
    S: "down",
};

const getMoveInfo = (raw: string) => {
    const prefix = raw.charAt(0);
    if (!["A", "D", "W", "S"].includes(prefix)) return "invalid";
    const suffix = raw.slice(1);
    const suffixDigit = parseInt(suffix);
    if (isNaN(suffixDigit)) return "invalid";
    if (suffixDigit.toString().length !== suffix.length) return "invalid";
    return {
        direction: directionMap[prefix],
        value: suffixDigit,
    };
};

全部评论

相关推荐

点赞 评论 收藏
分享
喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务