Codility: NumberOfDiscIntersections Solution

Lesson 6 Sorting

Implementation

1function solution(A) {
2 let i = 0
3
4 // 1 means beginning, -1 mean ending
5 const points = A.map((a, i) => [
6 [i - a, 1],
7 [i + a, -1],
8 ])
9 .reduce((acc, el) => {
10 acc[i++] = el[0]
11 acc[i++] = el[1]
12 return acc
13 }, [])
14 .sort((a, b) => a[0] - b[0] || b[1] - a[1])
15
16 let intersections = (activeCircles = 0)
17 for (const [_, place] of points) {
18 if (place === 1) {
19 intersections += activeCircles
20 activeCircles += 1
21 } else {
22 activeCircles -= 1
23 }
24 if (intersections > 1e7) {
25 return -1
26 }
27 }
28
29 return intersections
30}

References

http://www.lucainvernizzi.net/blog/2014/11/21/codility-beta-challenge-number-of-disc-intersections/

Comments

Loading comments...

Tags

codility

Next Post

Codility: MaxProductOfThree

Jan 22, 2021

Lesson 6 Sorting

Previous Post

Codility: Triangle

Jan 22, 2021

Lesson 6 Sorting

HoningJS

Search Posts