Skip to main content
added 432 characters in body
Source Link
Roland Illig
  • 21.4k
  • 2
  • 34
  • 83

Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function candidates(point, set) that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.

Grouping the points improves performance because grouping has complexity around \$\mathcal O(n)\$, where \$n\$ is the number of points.

Afterwards, finding the candidate points is a simple lookup: for each delta in (-2018, -1680, -1118, 0, 1118, 1860, 2018) you need one lookup, which again sums up to \$\mathcal O(n)\$.

In summary, the number of comparisons will be much less than the \$n\cdot n\$ from your current code.

Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function candidates(point, set) that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.

Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function candidates(point, set) that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.

Grouping the points improves performance because grouping has complexity around \$\mathcal O(n)\$, where \$n\$ is the number of points.

Afterwards, finding the candidate points is a simple lookup: for each delta in (-2018, -1680, -1118, 0, 1118, 1860, 2018) you need one lookup, which again sums up to \$\mathcal O(n)\$.

In summary, the number of comparisons will be much less than the \$n\cdot n\$ from your current code.

Source Link
Roland Illig
  • 21.4k
  • 2
  • 34
  • 83

Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function candidates(point, set) that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.