Story
Background is, I just finished an interview with examiner overseas. He gave me an algorithm question, that let me check a point if it’s included in a polygon.
At first, I lose my direction, not sure how to check. In the past 15 years, I’ve never met this kind of issue in projects. After some guiding from him, I find the way to check minutes later. We can draw a line to the diagram, and see how may crosses. Odd for inclusion, otherwise exclusion.
After the interview, I tried the code part, and done some research to compare the thought. There is one I want to share out:
Solution
Codes
try the following codes on JSBin or locally http server.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<link href="https://code.jquery.com/qunit/qunit-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/qunit/qunit-git.js"></script>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
class Solution {
constructor(points, target) {
this.points = points
this.target = target
}
solve() {
const n = this.points.length
const [testX, testY] = this.target
let c = false
for (let i = 0, j = n - 1; i < n; j = i++) {
const [iX, iY] = this.points[i]
const [jX, jY] = this.points[j]
if (
(iY > testY) !== (jY > testY) &&
(testX < (jX - iX) * (testY - iY) / (jY - iY) + iX)
) {
c = !c
}
}
return c
}
}
QUnit.module('pology', function() {
QUnit.test('triangle', function(assert) {
const points = [[5,5],[1,1],[6,1]]
assert.ok(new Solution(points, [5,4]).solve());
assert.ok(new Solution(points, [5,2]).solve());
assert.ok(new Solution(points, [3,3]).solve());
assert.notOk(new Solution(points, [5,5]).solve());
// assert.notOk(new Solution(points, [1,1]).solve()); // Special
assert.notOk(new Solution(points, [6,1]).solve());
});
QUnit.test('square', function(assert) {
const points = [[1,1],[1,2],[2,2],[2,1]]
assert.ok(new Solution(points, [1.1,1.1]).solve());
assert.notOk(new Solution(points, [0.9,0.9]).solve());
assert.ok(new Solution(points, [1, 1.1]).solve());
assert.ok(new Solution(points, [1.5, 1.5]).solve());
assert.notOk(new Solution(points, [0,0]).solve());
});
});
Result
Reference
An original solution named NPPoly from W. Randolph Franklin (WRF), you can check here.
Finally
Thanks to the examiner, really nice.
There are some further optimization to the question as well.
Guys, you are welcome to leave me message for further discussion. That will be very helpful on my math and mind growth. Thanks.