题解 | #坐标移动#

坐标移动

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 () {
    // Write your code here
    while(line = await readline()){
        const point = new Calc();
        const moves = getMoves(line);
        for (const m of moves) {
            point.move(m.direction, m.count)
        }

        console.log(point.output());
    }
}()


class Calc {
    constructor() {
        this.x = 0
        this.y = 0
    }

    move(direction, count) {
        if (direction === 'A') {
            this.x -= count
        }
        if (direction === 'D') {
            this.x += count
        }
        if (direction === 'W') {
            this.y += count
        }
        if (direction === 'S') {
            this.y -= count
        }
    }

    output() {
        return `${this.x},${this.y}`
    }
}

function isValid(input) {
    return /^[ADSW]\d{1,2}$/.test(input)
}

function extract(input) {
    const direction = input[0]
    const count = +input.slice(1)
    return {direction, count}
}

function getMoves(input) { 
    return input.split(";").filter(isValid).map(extract)
}

全部评论

相关推荐

03-28 19:11
铜陵学院 C++
有礼貌的山羊追赶太阳:太典了,连笔试都没有开始就因为HC满了而结束了,而且还卡你不让你再投其他部门的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务