1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オフラインどう書く第12回 参考問題解答例(TypeScript)

Last updated at Posted at 2013-06-22
class Turtle {
    private direction = 1;
    private pos = [0, 0];
    private way = 'A';
    private courseOut(course: string[]): boolean {
        return (
            course.length - 1 < this.pos[0] || this.pos[0] < 0 ||
            course[this.pos[0]][this.pos[1]] === '*' || course[this.pos[0]][this.pos[1]] === undefined);
    }
    turn(direction: string) {
        if (direction === 'L') {
            this.direction = this.direction === 0 ? 3 : this.direction - 1;
        } else {
            this.direction = this.direction === 3 ? 0 : this.direction + 1;
        }
    }
    walk(steps: number, directions: number[][], course: string[]) {
        for (var i = 0; i < steps; ++i) {
            this.pos[0] += directions[this.direction][0];
            this.pos[1] += directions[this.direction][1];
            if (this.pos[0] === course.length && this.direction === 2) {
                this.direction = 0;
                this.pos[0] -= 2;
                this.pos[1] = course[this.pos[0]].length - 1 - this.pos[1];
            }
            if (this.courseOut(course)) {
                this.way += '?';
                return;
            }
            this.way += course[this.pos[0]][this.pos[1]];
        }
    }
    getWay(): string {
        return this.way;
    }
}

var solve = (src: string): string => {
    var cource = [
        'ABCDEFGHIJK', 'LMNOPQRSTUV', 'WXYZabcdefg',
        'hij*****765', 'klm*****432', 'nop*****10z',
        'qrs*****yxw', 'tuv*****vut'];
    var directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];
    var turtle = new Turtle();
    for (var i = 0; i < src.length; ++i) {
        var c = src[i];
        if (c === 'L' || c === 'R') {
            turtle.turn(c);
            continue;
        }
        var steps = parseInt(c, 16);
        turtle.walk(steps, directions, cource);
        if (turtle.getWay().indexOf('?') != -1) {
            break;
        }
    }
    return turtle.getWay();
}

var test = (src: string, expected: string) => {
    var actual = solve(src);
    var result = expected === actual ? 'ok' : '***ng***';
    console.log(result);
}

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?