题解 | #坐标移动#
坐标移动
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]}`);
查看11道真题和解析