题解 | #坐标移动#

坐标移动

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

let directives = readline().split(';');
// 指令校验表达式
const reg = /^[ADWS](?:[0-9]|[1-9][0-9]{1})$/;
// 保留有效的指令
directives = directives.filter(d => {
  return reg.test(d);
});
// 坐标[x, y]
const coord = [0, 0];
function directExecutor(d) {
  const reg = /^([ADWS])([0-9]|[1-9][0-9]{1})$/;
  const [, direction, step] = reg.exec(d);
  switch(direction) {
    case 'A':
      coord[0] -= Number.parseInt(step, 10);
      break;
    case 'D':
      coord[0] += Number.parseInt(step, 10);
      break;
    case 'W':
      coord[1] += Number.parseInt(step, 10);
      break;
    case 'S':
      coord[1] -= Number.parseInt(step, 10);
      break;
  }
}
directives.forEach(d => {
  directExecutor(d);
});

console.log(`${coord[0]},${coord[1]}`);

全部评论

相关推荐

05-29 09:02
门头沟学院 Java
点赞 评论 收藏
分享
鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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