Maximum Number of Visible Points LeetCode solution in JavaScript

1
// basically First i transform my points into degrees in regards to my location as the center
2
// I need to perform a sliding window to see how many points can fit within my window of length
3
// angle
4
var visiblePoints = function (points, angle, location) {
5
//Math.atan2(y,x) returns the ANGLE in RADIANS between the point (X,Y), the CENTER (0,0) and x'x
6
// so Math.atan2(5,5) * (180/Math.pi) === 45 //transforms it from radians to degrees instead
7
let [sx, sy] = location;
8
let onCenter = points.filter(([x, y]) => x == sx && y == sy).length; //if i m standing on a point i always count it
9

10
points = points
11
.filter(([x, y]) => !(x == sx && y == sy)) //other than that i dont want it messing with my result
12

13
.map(([x, y]) => {
14
// i need to transform my center from (0,0) to location, hence (y-sy,x-sx)
15
return Math.atan2(y - sy, x - sx) * (180 / Math.PI); //returns the degrees
16
})
17
.sort((a, b) => a - b);
18

19
//I will now perform the circular array duplication trick in order to consider points from different view
20
points = [...points, ...points.map((d) => d + 360)];
21
// so for example if a point is 340, it can go with a point that is 15
22
// example : [0,60,230,250,359], angle=200
23
// would become [0,60,230,250,359,360,420,590,610,719]
24
// would allow me to pick * * * * * ,which is practically [230,250,359,0,60]
25
// (every element of my starting array), which are obviously visible with anangle fo 200 deg
26

27
//now i will perform a sliding window that tracks the points visible from my current degree-my angle degrees
28
let start = 0,
29
n = points.length,
30
result = 0;
31
for (let end = 0; end < n; end++) {
32
while (start < end && points[start] < points[end] - angle)
33
//if the point of start is no bueno
34
start++; // shrink the window until all the points are within angle degrees
35
result = Math.max(result, end - start + 1);
36
}
37
return result + onCenter; //the points i can see + the ones i ms tanding on
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0