题解 | #坐标移动#
坐标移动
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, }; };