-
Notifications
You must be signed in to change notification settings - Fork 5
/
day12.js
129 lines (113 loc) · 3.31 KB
/
day12.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
const fs = require('fs');
const lines = fs.readFileSync('day12.txt', {encoding: 'utf-8'}).split('\n').filter(x => x);
const directionToCoord = {
0: 'E',
1: 'N',
2: 'W',
3: 'S',
}
class Boat {
constructor() {
this.x = 0;
this.y = 0;
this.direction = 0;
}
move(char, number) {
switch(char) {
case 'N':
this.y += number;
break;
case 'S':
this.y -= number;
break;
case 'E':
this.x += number;
break;
case 'W':
this.x -= number;
break;
case 'L':
this.direction = ((this.direction + (number / 90)) + 4)%4;
break;
case 'R':
this.direction = ((this.direction - (number / 90)) + 4)%4;
break;
case 'F':
this.move(directionToCoord[this.direction], number);
break;
default:
throw new Error('Not implemented: ' + char);
break;
}
}
getPosition() {
return Math.abs(this.x) + Math.abs(this.y);
}
}
const boat = new Boat();
lines.forEach(line => {
const {groups} = /^(?<char>.)(?<number>\d+)$/.exec(line);
boat.move(groups.char, parseInt(groups.number));
// console.log(boat.x, boat.y);
})
console.log(boat.getPosition());
class BetterBoat {
constructor() {
this.x = 0;
this.y = 0;
this.dx = 10;
this.dy = 1;
}
move(char, number) {
switch(char) {
case 'N':
this.dy += number;
break;
case 'S':
this.dy -= number;
break;
case 'E':
this.dx += number;
break;
case 'W':
this.dx -= number;
break;
case 'L':
{
let angle = number * Math.PI / 180;
let dx = this.dx*Math.cos(angle) - this.dy*Math.sin(angle);
let dy = this.dx*Math.sin(angle) + this.dy*Math.cos(angle);
this.dx = Math.round(dx);
this.dy = Math.round(dy);
}
break;
case 'R':
{
let angle = -number * Math.PI / 180;
let dx = this.dx*Math.cos(angle) - this.dy*Math.sin(angle);
let dy = this.dx*Math.sin(angle) + this.dy*Math.cos(angle);
this.dx = Math.round(dx);
this.dy = Math.round(dy);
}
break;
case 'F':
this.x += number*this.dx;
this.y += number*this.dy;
break;
default:
throw new Error('Not implemented: ' + char);
break;
}
}
getPosition() {
return Math.abs(this.x) + Math.abs(this.y);
}
}
const betterBoat = new BetterBoat();
// console.log(betterBoat.x, betterBoat.y);
lines.forEach(line => {
const {groups} = /^(?<char>.)(?<number>\d+)$/.exec(line);
betterBoat.move(groups.char, parseInt(groups.number));
// console.log(betterBoat.x, betterBoat.y);
})
console.log(betterBoat.getPosition());