-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobot.js
218 lines (176 loc) · 5.18 KB
/
robot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
var _ = require('lodash');
var fs = require('fs');
var readline = require('readline');
// We know from basic mathematics that we can conveniently represent both
// locations and differences in location (i.e. movements) through the same
// abstraction - vectors from the origin. Vectors can be added together,
// allowing us to combine a location with any number of movements to determine
// a new position.
class Vector {
constructor(x, y) {
if (!_.isInteger(x) || !_.isInteger(y)) {
throw new Error("Can't construct an integer vector from non-integer(s): "
+ x + ', ' + y);
}
this._x = x;
this._y = y;
}
get x() {
return this._x;
}
get y() {
return this._y;
}
equals(other) {
return this._x === other._x && this._y === other._y;
}
add(other) {
return new Vector(this._x + other._x, this._y + other._y);
}
}
class SimpleGrid {
constructor(width, height) {
if (!_.every([
_.isInteger(width),
_.isInteger(height),
width > 0,
height > 0,
])) {
throw new Error('Can only construct SimpleGrid with positive integers '
+ '(' + width + ', ' + height + ')');
}
this._width = width;
this._height = height;
}
navigable(location) {
return 0 <= location.x && location.x < this._width
&& 0 <= location.y && location.y < this._height;
}
}
// Get the number n, where 0 <= n < divisor, such that,
// quotient === k * divisor + n, for some integer k
function positiveMod(quotient, divisor) {
var regularMod = quotient % divisor;
return regularMod < 0 ? regularMod + Math.abs(divisor) : regularMod;
}
class Direction {
static get _count() {
return 4;
}
static get _stringValues() {
return ['NORTH', 'EAST', 'SOUTH', 'WEST'];
}
static get _unitMovements() {
return [
new Vector(0, 1),
new Vector(1, 0),
new Vector(0, -1),
new Vector(-1, 0),
];
}
constructor(clockwiseRightAngles) {
this._clockwiseRightAngles =
positiveMod(clockwiseRightAngles, this.constructor._count);
}
static fromString(str) {
var ix = this._stringValues.indexOf(str);
if (ix ===- 1) {
throw new Error('Invalid value for constructing a Direction');
} else {
return new Direction(ix);
}
}
toString() {
return this.constructor._stringValues[this._clockwiseRightAngles];
}
_rotateBy(clockwiseRightAngles) {
return new Direction(this._clockwiseRightAngles + clockwiseRightAngles);
}
rotateLeft() {
return this._rotateBy(-1);
}
rotateRight() {
return this._rotateBy(1);
}
// Get the unit (length 1) movement in this direction:
unitMovement() {
return this.constructor._unitMovements[this._clockwiseRightAngles];
}
}
class Robot {
constructor() {
this.grid = new SimpleGrid(5, 5);
}
processCommands(input) {
_(input.split('\n'))
.map(cmd => cmd.trim()) // stripe out extraneous ws for convenience
// Any command prior to a PLACE is invalid and should be ignored:
.dropWhile(cmd => !cmd.startsWith('PLACE'))
.map(cmd => cmd.split(' '))
.forEach(([cmdName, argStr]) => {
if (!_.includes(['PLACE', 'LEFT', 'RIGHT', 'MOVE', 'REPORT'], cmdName)) {
throw new Error('Invalid command given to robot: ' + cmdName);
}
var args;
if (cmdName === 'PLACE') {
args = argStr.split(',');
args[0] = parseInt(args[0]);
args[1] = parseInt(args[1]);
} else {
args = [];
}
var methodName = cmdName.toLowerCase();
this[methodName](...args);
});
}
place(x, y, facing) {
var newLocation = new Vector(x, y);
if (this.grid.navigable(newLocation)) {
this.location = newLocation;
this.direction = Direction.fromString(facing);
}
// otherwise ignore the invalid place command
}
left() {
this.direction = this.direction.rotateLeft();
}
right() {
this.direction = this.direction.rotateRight();
}
move() {
var newLocation = this.location.add(this.direction.unitMovement());
if (this.grid.navigable(newLocation)) {
this.location = newLocation;
}
}
report() {
console.log([this.location.x, this.location.y, this.direction.toString()]
.join(','));
}
}
// Read from stdin only if this is being executed as a script, not imported:
// https://nodejs.org/docs/latest/api/all.html#modules_accessing_the_main_module
if (require.main === module) {
process.stdin.setEncoding('utf-8');
var terminal = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
var isTty = process.stdin.isTTY;
terminal.setPrompt('> ');
var maybePrompt = () => isTty ? terminal.prompt() : undefined;
var maybeLog = str => isTty ? console.log(str) : undefined;
var input = [];
maybePrompt();
terminal.on('line', line => {
input.push(line);
maybePrompt();
});
terminal.on('close', () => {
maybeLog('\n'); // separate input and output;
var r2d2 = new Robot();
r2d2.processCommands(input.join('\n'));
});
}
// Export components (primarily for testing)
module.exports = {Vector, SimpleGrid, Direction, Robot};