Last active
February 24, 2020 08:20
-
-
Save jlmakes/739f0bfef9a6201f3eea02da981550f9 to your computer and use it in GitHub Desktop.
JavaScript Quiz and Answer
This file contains hidden or 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
let answer = runTest(); | |
console.log(answer); | |
// do not alter the code below this point | |
function createPoints(randomizedIndex) { | |
var startY = Math.random() * 100; | |
var slope = Math.random(); | |
var points = []; | |
for (var i = 0; i < 10; i++) { | |
var x = Math.random() * 100; | |
points.push({ x: x, y: x * slope + startY }); | |
} | |
var outlier = points[randomizedIndex]; | |
outlier.y += Math.random() > 0.5 ? 10 : -10; | |
return points; | |
} | |
function runTest() { | |
var outlierIndex = Math.floor(Math.random() * 10); | |
var points = createPoints(outlierIndex); | |
return findOutlier(points) === points[outlierIndex]; | |
} | |
function findOutlier() { | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactoring
With a little more time to think through my implementation, I think the main issue is that for any given point P, I was calculating its slope by using P and P+1 — which is ultimately where the off by one error comes from. I think a better approach would be to define the slope of a given point P by both neighbors, resulting in a 2-tuple (as array), e.g:
Doing this for each
point
inpoints
would result in a 2-dimensional array of slopes, where theoutlierIndex
would be where both values in the slope tuple differ from the line’s slope. (In the example below, that would be6
) e.g:This approach of course requires determining the line's slope, which in this case would be the most common value found in the 2-dimensional array of slopes — using a hash map to track each slope and its number of occurrences is the first strategy that comes to mind.
Revised Solution