I’m writing a bit of JavaScript code which should select a random item from a canvas if the item meets certain requirements. There are different kinds of items (circles, triangles, squares etc.) and there’s usually not the same number of items for each kind. The items are arranged in a hierarchy (so a square can contain a few circles, and a circle can contain other circles and so on – they can all be nested).
Right now, my (primitive) approach at selecting a random item is to:
- Recursively traverse the canvas and build a (possibly huge!) list of items
- Shuffle the list
- Iterate the shuffled list from the front until I find an item which meets some extra requirements.
The problem with this is that it doesn’t scale well. I often run into memory issues because either the recursion depth is too high or the total list of items becomes too large.
I was considering to rewrite this code so that I consider choosing elements as I traverse the canvas – but I don’t know how I could “randomly” choose an element if I don’t know how many elements there are in total.
Does anybody have some idea how to solve this?
Start with
max_r = -1andrand_node = null. Iterate through the tree. For each node meeting the criteria:At the end
rand_nodewill be a randomly selected node with only a single iteration required.