-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaxiCabGeometryClass.js
65 lines (57 loc) · 1.55 KB
/
TaxiCabGeometryClass.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
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(distance, vector) {
const [dx, dy] = vector.getDirection();
this.x += dx * distance;
this.y += dy * distance;
}
}
class Vector {
directions= [
[0, 1], // north
[1, 0], // east
[0, -1], // south
[-1, 0] // west
];
constructor(dirIndex) {
this.dirIndex = dirIndex;
}
getDirection() {
return this.directions[this.dirIndex];
}
turnLeft(position) {
if (this.dirIndex === 0 && position.x === 0) {
this.dirIndex = 0;
} else {
this.dirIndex = (this.dirIndex + this.directions.length - 1) % this.directions.length;
}
}
turnRight(position) {
if (this.dirIndex === 1 && position.y === 0) {
this.dirIndex = 1;
} else {
this.dirIndex = (this.dirIndex + 1) % this.directions.length;
}
}
}
const blocksAway = function(directions) {
let position = new Position(0, 0);
let vector = new Vector(0);
for (let i = 0; i < directions.length; i += 2) {
const turnDirection = directions[i];
const distance = directions[i + 1];
if (turnDirection === "left") {
vector.turnLeft(position);
} else {
vector.turnRight(position);
}
position.move(distance,vector);
}
return { east: position.x, north: position.y };
};
console.log(blocksAway(["right", 2, "left", 3, "left", 1]));
console.log(blocksAway(["left", 1, "right", 1, "left", 1, "right", 1, "left", 1, "right", 1]));
console.log(blocksAway(["left", 3, "right", 1, "right", 3, "right", 1]));