题解 | #坐标移动#

坐标移动

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

let commendStr = readline()

/** 给定原坐标,移动方向及移动距离,返回移动后的坐标 */
const move = ({x, y}, direction, distance) => {
    if (direction === 'A') {
        x -= distance
    } else if (direction === 'W') {
        y += distance
    } else if (direction === 'S') {
        y -= distance
    } else if (direction === 'D') {
        x += distance
    }
    return {
        x, 
        y        
    }
}

/** 处理坐标字符串,移除不合法的坐标 */
const commends = (commendStr.split(';')).filter((commend) => {
    return ['A', 'W', 'S', 'D'].includes(commend.charAt(0)) && !isNaN(commend.substring(1))
})

/** 初始坐标 */
let coord = {
    x: 0,
    y: 0
}

/** 遍历所有坐标,得到最终结果 */
commends.forEach(commend => {
    coord = move(coord, commend.charAt(0), +commend.substring(1))
})

console.log(`${coord.x},${coord.y}`)

全部评论

相关推荐

06-20 19:40
中原工学院 Java
网络存储:十几天不会让你拉人办卡就结束了吧?
点赞 评论 收藏
分享
05-07 19:10
已编辑
中国科学技术大学 C++
silly01:现在先去 momenta,8-9月去鹅找日常实习,八股文算法背好了你这随便进。不过建议补充一下后端知识,MySQL、Redis看下八股,再补个6824,加点go后台的技术栈,9月随便进大厂。CPP后端只能来WXG
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务