randomgraphicspixel

Accessing every cordinate on a plane in random order, uniquely efficiently in time and space


I currently have a program where I need to access every pixel of an image in random order. My current approach is to store all cordinate combinations and shuffle them, but this leads to too much memory usage for larger images and results in an out of memory crash.

Is there some function where f(1) -> f(n*n) covers all cordinates uniquely but in random order without using too much time or space?

It doesen't have to be completely random, the points selected just have to be spread out. It would be preferable for it to be in Javascript but an explanation is also fine.


Solution

  • You could build a custom linear congruential generator or find one with a cycle of at least n * n (but preferably not much greater). Discard outcomes n * n or larger. For non-discarded values i in the range 0 <= i < n*n, decompose into (x,y) pairs using a very old trick: x <- floor(i / n) and y <- i % n.