JSFiddle - React, Tailwind, and code Playground
Find the most trees
by Torsten Walter
HTML
<div id="out"></div>
JavaScript
const out = document.getElementById('out');
const treeList = [
{x: 1, y: 1},
{x: 2, y: 2},
{x: 3, y: 3},
{x: 1.5, y: 3}
]
const viewingAngle = 30
function toPolar ({x, y}) {
return {
angle: Math.round(Math.atan2(y, x) * 180 / Math.PI * 100) /100,
r: Math.sqrt(x*x + y*y)}
}
function bestAngle (alpha, trees) {
const uniqueTrees = trees.map(toPolar)
.reduce((acc, tree) => acc.add(tree.angle), new Set())
let direction = 0;
[...uniqueTrees]
.sort((a,b) => a - b)
.reduce((prevMax, angle, idx, list) => {
let max = 0
for (let i = idx; i < list.length; i++) {
max += 1
}
return max > prevMax ? max : prevMax
})
return 1
}
out.innerHTML = JSON.stringify(bestAngle(viewingAngle, treeList), null, 2)