题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { let arr = []; const findArr = ["A", "D", "W", "S"]; // Write your code here while ((line = await readline())) { // 判断第一个字母是不是 正确的 后面的字符串要纯数字的 可以使用js 内置方法 isNaN 是数字 则返回false 也可以使用正则 /^\d+$/ arr = line .split(";") .map((item) => [item[0], item?.slice(1)]) .filter( ([first, rest]) => findArr.indexOf(first) > -1 && !isNaN(rest) ); // 计算坐标 0,0 // reduce 是累加的值 const a = arr.reduce( (sum, item) => { let [first, last] = sum; let [itemFirst, itemLast] = item; // console.log([first,last],[itemFirst,itemLast]) switch (itemFirst) { case findArr[0]: first -= parseInt(itemLast); break; case findArr[1]: first += parseInt(itemLast); break; case findArr[2]: last += parseInt(itemLast); break; case findArr[3]: last -= parseInt(itemLast); break; } return [first, last]; }, [0, 0] ); console.log(a.join()); } })();
zhouya——的方法
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here while ((line = await readline())) { let arr = line.split(";"); let reg = /^[A|D|W|S][0-9]+$/; let x = 0; let y = 0; for (let i = 0; i < arr.length; i++) { // 符合 if (reg.test(arr[i])) { let direction = arr[i].slice(0, 1); let length = Number(arr[i].slice(1)); // console.log('符合的数', direction, length) switch (direction) { case "A": x -= length; break; case "D": x += length; break; case "W": y += length; break; case "S": y -= length; break; } } } console.log(x + "," + y); } })();
better贝塔——的方法
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void async function () { // Write your code here while(line = await readline()){ const arr = line.split(';'); const reg = /^[WASD]\d\d?$/; const filArr = arr.filter(item => reg.test(item) === true); let x = 0, y = 0; filArr.forEach(item => { let direction = item.substring(0,1); let num = Number(item.substring(1)); switch(direction){ case 'W': y += num;break; case 'A': x -= num;break; case 'S': y -= num;break; case 'D': x += num;break; default:x=0;y=0; } }); console.log([x,y].join(',')); } }()
卡西莫多之虹——的方法
练练练练练 文章被收录于专栏
练练练练练