r/dailyprogrammer • 3 1 • Apr 16 '12

[4/16/2012] Challenge #40 [difficult]

Make a function that generates an array of 1,000 2-dimensional points, where both the x-coordinate and the y-coordinate are between 0.0 and 1.0. So (0.735, 0.167) and (0.456, 0.054) would be examples. (Most computer languages have a simple random function that returns a double precision floating point number in this range, so you can use that to generate the coordinates. Python has random.random(), Java has Math.random(), Perl has rand(), etc. )

Create a program that finds the two points in this array that are closest to each other, and print that distance. As a reminder, the distance between the two points (x1, y1) and (x2, y2) is sqrt( (x1 - x2)2 + (y1 - y2)2 ).

Bonus 1: Do the same thing, but instead of using 1,000 points, use 1,000,000 points and see if you can create an algorithm that runs in a reasonable amount of time [edit: something like one minute or less].

Bonus 2: Do the same thing but for 3-dimensional points.

14 Upvotes

32 comments sorted by

View all comments

Show parent comment

0

u/Cosmologicon 2 3 Apr 17 '12

Argh, that's so frustrating! This is almost exactly the same as the algorithm I came up with back in the original idea thread, the one that takes hours to run. The only difference is that I used range instead of xrange, which boosts it from O(n log n) to O(n2 ). I feel dumb now.

2

u/Cosmologicon 2 3 Apr 17 '12

Sure enough, I just tried adding a single character to my code from last month, and it now completes in 5 seconds. Here it is:

from random import random
from math import *

npoints = 1000000

ps = [(random(), random()) for _ in range(npoints)]
ps.sort()
mind, mind2 = 10, 100
for i, (x0, y0) in enumerate(ps):
    for j in xrange(i+1,npoints):
        x1, y1 = ps[j]
        if x1 > x0 + mind: break
        d2 = (x0 - x1) ** 2 + (y0 - y1) ** 2
        if d2 < mind2:
            mind2 = d2
            mind = sqrt(d2)
print mind

1

u/oskar_s Apr 17 '12

See, this is why you never use range() in a for-loop, you always use xrange :) Let this be a lesson!