{
const points = [...asteroids.keys()];
const station = points.reduce((a, b) => asteroids.get(a) > asteroids.get(b) ? a : b);
const toVaporize = points.filter(p => p !== station);
const sortDist = (a, b) => {
return (
Math.abs(station.x - a.x) +
Math.abs(station.y - a.y) -
(Math.abs(station.x - b.x) + Math.abs(station.y - b.y))
);
};
const anglesToPoints = new Map();
toVaporize.forEach(point => {
const angle = (180 / Math.PI) * Math.atan2(point.x - station.x, point.y - station.y);
if (anglesToPoints.has(angle)) {
anglesToPoints.set(
angle,
anglesToPoints
.get(angle)
.concat([point])
.sort(sortDist)
);
} else {
anglesToPoints.set(angle, [point]);
}
});
const sortedAngles = [...anglesToPoints.keys()].sort((a, b) => a - b);
let i = sortedAngles.indexOf(180);
let destroyed = 0;
while (true) {
const angleOfAttack = sortedAngles[i];
const target = anglesToPoints.get(angleOfAttack).shift();
if (target) {
destroyed++;
}
if (destroyed === 200) {
return target.x * 100 + target.y;
}
i--;
if (i === -1) {
i = sortedAngles.length - 1;
}
}
}