Created
February 25, 2017 19:53
-
-
Save mpalmerlee/aec6446dbac5aa44f25d732b130f2671 to your computer and use it in GitHub Desktop.
Maximum Number of points on a line from origin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* line {x,y,dx,dy} */ | |
var points = [{x:1,y:1},{x:2,y:2},{x:1,y:2},{x:1,y:3},{x:1,y:4}]; | |
var maxNumberOfPoints = 1; | |
points.forEach(function(pointA) { | |
var numberOfPointsA = 1; | |
var atan = Math.atan2(pointA.y, pointA.x); | |
points.forEach(function(pointB) { | |
if(pointA == pointB) { | |
return; | |
} | |
var atanJ = Math.atan2(pointB.y, pointB.x); | |
if(atanJ == atan || Math.abs(atanJ) + Math.abs(atan) == Math.PI) { | |
//we got one! | |
numberOfPointsA++; | |
} | |
}); | |
maxNumberOfPoints = Math.max(numberOfPointsA, maxNumberOfPoints); | |
}); | |
console.log("maxNumberOfPoints atan2:", maxNumberOfPoints); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the help @nfreymuth-telepathy
I guess my brain wasn't firing on all cylinders on Friday. I've changed your code a bit to account for more test cases, instead of tracking only the last angle I needed to keep an object (hash/map) to track the counts at each angle, this now works for all of my test cases:
I'm not sure what should be returned in the case there are duplicate points, right now it doesn't de-duplicate so it counts dupes towards the max.
Obviously if I was doing this for real I would use a real unit test suite like mocha or tape, but my poor mans un-comment method works for this :)