0

TL;DR Randomly access every tile in a tilemap

I have a way of generating random positions of tiles by just filling an entire layer of them (its only 10x10) then running a forloop like for (int x = 0; x < 13; x++) { for (int y = 0; y < 11; y++)}} Where I randomly delete tiles. I also have a cap to this, which is at about 30. The problem is that when the loop runs over, it uses up the cap to the left (Because it starts at x=0 y=0 then does x0 x1 x2 x3 ...). I tried randomly generating coordinates, but this didn't work because it doesnt go over all the coordinates.

Does anyone know a better practice for scanning over every coordinate in a map in random order?

Oscar Apeland
  • 6,422
  • 7
  • 44
  • 92

2 Answers2

1

Number your tiles 0 to n anyway you want. Create a NSMutableIndexSet, and add all to it. Use a random number generator scaled to the number of items still in the index set (actually the range of first to last), grab one, then remove it from the set. If the random number is not in the set generate a new be, etc, until you find one in the set.

David H
  • 40,852
  • 12
  • 92
  • 138
1

I think the best practice to accomplish this is via double hashing. To find out more read this link: Double Hashing. I will try to explain it simply.

You have two auxiliary hash functions which need to be pre-computed. And a main hash function which will run in a for loop. Lets test this out (this will be pseudo code):

key = random_number() //lets get a random number and call it "key"
module = map_size_x // map size for our module

//form of hash function 1 is: h1(key) = key % module, lets compute the hash 1 for our main hash function
aux1 = key % module
//form of hash function 2 is: h2(key) = 1 + (key % module'), where module' is module smaller for a small number (lets use 1), lets compute it:
aux2 = 1 + (key % (module - 1))

//the main hash function which will generate a random permutation is in the form of: h(key, index) = (h1(key) + index*h2(key)) % module. we already have h1 and h2 so lets loop this through:
for (i = 0; i < map_size_x; i++)
{
     randomElement = (aux1 + i*aux2) % module //here we have index of the random element
     //DO STUFF HERE
}

To get another permutation simply change the value of key. For more info check the link.

Hope this helps. Cheers.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Majster
  • 3,611
  • 5
  • 38
  • 60