Created
July 17, 2022 08:05
-
-
Save karpolan/895e7aa06f5dd568f6fb32ae1ce651b1 to your computer and use it in GitHub Desktop.
Some code challenge, working but not scalable well. Silver medal :)
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
function solution(X, Y, colors) { | |
let countG = 0; | |
let countR = 0; | |
let points = [] | |
for (let i = 0; i < colors.length; i++) { | |
const distance = Math.sqrt(X[i]**2 + Y[i]**2) | |
const color = colors[i] | |
points.push({distance, color}) | |
if (color === 'R') { | |
countR++ | |
} else { | |
countG++ | |
} | |
} | |
if (countG < 1 || countR < 1 ) { | |
return 0; // There is no points of some color | |
} | |
points = points.sort((a, b) => a.distance - b.distance) | |
distances = [...new Set(points.map((current) => current.distance))].sort((a, b) => b - a); | |
let possibleCircles = [] | |
for (const distance of distances) { | |
const pointsInside = points.filter((point) => point.distance <= distance); | |
const {r, g} = pointsInside.reduce((result, point) => { | |
let {r, g} = result; | |
if (point.color === 'R') { | |
r++ | |
} else { | |
g++ | |
} | |
return {r, g} | |
} , {r: 0, g: 0}) | |
if (r === g) { | |
possibleCircles.push({radius: distance, pointCount: r + g}) | |
} | |
} | |
if (possibleCircles.length < 1) { | |
return 0; // It is not possible to draw a circle | |
} | |
return possibleCircles.sort((a, b) => b.pointCount - a.pointCount)[0].pointCount || 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can add cache for previous
pointsInside
and counts, because iteration bydistances
will filter and verify all points from previous iteration