In today’s Programming Praxis exercise, our goal is to find the 100 points closest to (0, 0) out of a list of 1000000 random points in O(n). Let’s get started, shall we?

Some imports:

import Control.Applicative import qualified Data.IntMap as I import System.Random

The obvious solution is to simply sort the list and take the first 100 elements. Sorting, however, usually takes O(n log n), which is not allowed. Fortunately, by using the square of the distance rather than the distance we not only save a million square root operations, but it also makes the value we’re sorting by an integer, which allows us to use an IntMap that has O(1) insertion and thus O(n) sorting.

closest :: Int -> [(Int, Int)] -> [(Int, Int)] closest n = take n . concat . I.elems . I.fromListWith (flip (++)) . map (\(x,y) -> (x*x+y*y, [(x,y)]))

To test, we need a million random points.

points :: IO [(Int, Int)] points = take 1000000 <$> liftA2 zip (randomRs (-1000, 1000) <$> newStdGen) (randomRs (-1000, 1000) <$> newStdGen)

Finally we run the algorithm.

main :: IO () main = print . closest 100 =<< points

To see whether our algorithm is truly linear, let’s look at some timings:

1 million: 2.9 s 2 million: 5.7 s 4 million: 11.6 s 8 million: 23.8 s

Looks fairly linear to me.