-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve.js
210 lines (185 loc) · 6.07 KB
/
solve.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
console.time("d15");
const rl = require("./utils").getInputRL("d15.txt");
const FREE = ".";
const ELF = "E";
const GOBLIN = "G";
const DEFAULT_ATTACK = 3;
const DEFAULT_HP = 200;
function programReadLine(rl) {
let MAP = [];
rl.on("line", line => {
MAP.push(line.split("")); // MAP[y][x] = contents of [x,y] spot
});
rl.on("close", () => {
console.log(
"Answer (part I):",
run(JSON.parse(JSON.stringify(MAP))).outcome
);
let part2result = null;
let elfAttack = DEFAULT_ATTACK;
do {
elfAttack++;
part2result = run(JSON.parse(JSON.stringify(MAP)), elfAttack, true);
} while (!part2result); // keep trying until combat hasn't been aborted
console.log("Answer (part II):", part2result.outcome, "(finally!)");
console.timeEnd("d15");
});
}
function run(map, elfAttack = DEFAULT_ATTACK, abortIfElfDies = false) {
let players = initPlayers(map, elfAttack);
let data = {
map: map,
players: players,
round: 0,
outcome: null,
elfAttack: elfAttack
};
round: while (true) {
players = players.sort((p1, p2) =>
p1.pos.y === p2.pos.y ? p1.pos.x - p2.pos.x : p1.pos.y - p2.pos.y
);
for (let i = 0; i < players.length; i++) {
player = players[i];
if (player.alive) {
// if there are no enemies left, game ends
if (players.filter(p => p.alive && p.type !== player.type).length < 1) {
break round;
}
let enemy = findEnemyToAttack(player, players);
let next = enemy ? null : findNextMovement(player, players, map);
if (!enemy && next) {
map[player.pos.y][player.pos.x] = FREE;
player.pos.x = next.x;
player.pos.y = next.y;
map[player.pos.y][player.pos.x] = player.type;
// once we moved, check again if an enemy is at range
enemy = findEnemyToAttack(player, players);
}
if (enemy) {
// attack
enemy.hp -= player.attack;
if (enemy.hp < 1) {
// we killed him! mark him as dead
enemy.alive = false;
map[enemy.pos.y][enemy.pos.x] = FREE;
if (enemy.type === ELF && abortIfElfDies) return null;
}
}
}
}
data.round++;
//printStatus(data);
}
// outcome = completed rounds * remaining hit points
data.outcome =
data.round *
players
.filter(p => p.alive)
.map(p => p.hp)
.reduce((acc, curr) => acc + curr, 0);
return data;
}
function initPlayers(map, elfAttack = DEFAULT_ATTACK) {
let players = [];
map.forEach((row, y) => {
row.forEach((cell, x) => {
if (cell === ELF || cell === GOBLIN) {
players.push({
type: cell,
hp: DEFAULT_HP,
attack: cell === ELF ? elfAttack : DEFAULT_ATTACK,
alive: true,
pos: { x, y }
});
}
});
});
return players;
}
function findEnemyToAttack(player, allPlayers) {
return (
allPlayers
// discard allies and dead players (that will already discard himself)
.filter(p => p.type !== player.type && p.alive)
// get only those within range
.filter(
p =>
(Math.abs(p.pos.x - player.pos.x) === 1 &&
p.pos.y === player.pos.y) ||
(Math.abs(p.pos.y - player.pos.y) === 1 && p.pos.x === player.pos.x)
)
// find the weakest one (in tie, the first found in order prevails)
.reduce(
(weakest, curr) =>
weakest === null || weakest.hp > curr.hp ? curr : weakest,
null
)
);
}
function findNextMovement(player, allPlayers, map) {
let targetKeys = {}; // "x,y" ==> { x, y } of alive enemy
allPlayers
.filter(p => p.alive && p.type !== player.type)
.map(p => getAdjacents(p.pos).filter(pos => map[pos.y][pos.x] === FREE))
.reduce((acc, list) => acc.concat(...list), [])
.forEach(pos => (targetKeys[`${pos.x},${pos.y}`] = pos));
let visited = {};
visited[`${player.pos.x},${player.pos.y}`] = true;
let paths = [[player.pos]];
while (true) {
let newPaths = [];
let targetPaths = [];
paths.forEach(path => {
let adjacents = getAdjacents(path[path.length - 1]);
adjacents.forEach(adj => {
let xy = `${adj.x},${adj.y}`;
if (targetKeys[xy]) {
// found a path to a target!
// add it so at the end of the iteration we chose the right one based on enemy order
targetPaths.push([...path, adj, targetKeys[xy]]);
} else if (!visited[xy] && map[adj.y][adj.x] === FREE) {
// new extended path to explore at next iteration
newPaths.push([...path, adj]);
}
visited[xy] = true; // mark as visited so other paths ignore it
});
});
if (targetPaths.length > 0) {
// we got one or more paths reaching a target for the first time, here is where our search ends
// if we found multiple shortest paths, use the one that reaches the first target according top-to-bottom/left-to-right order
targetPaths = targetPaths.sort((p1, p2) =>
p1[p1.length - 1].y === p2[p2.length - 1].y
? p1[p1.length - 1].x - p2[p2.length - 1].x
: p1[p1.length - 1].y - p2[p2.length - 1].y
);
// return the first step to take for the shortest path ([0] is the player current position)
return targetPaths[0][1];
}
// no paths to a target found yet, keep iterating with the paths after one more step
paths = newPaths;
if (paths.length < 1) return null; // no reachables targets, search ends without a result
}
}
function getAdjacents(pos) {
return [
{ x: pos.x, y: pos.y - 1 },
{ x: pos.x - 1, y: pos.y },
{ x: pos.x + 1, y: pos.y },
{ x: pos.x, y: pos.y + 1 }
];
}
function printStatus(data) {
console.log("After round", data.round);
printMap(data.map);
printPlayers(data.players, true);
console.log();
}
function printMap(map) {
console.log(map.map(row => row.join("")).join("\n"));
}
function printPlayers(players, onlyAlive) {
players
.filter(p => !onlyAlive || p.alive)
.forEach(p => console.log(p.type, p.pos.x, p.pos.y, p.hp));
}
programReadLine(rl);