Page 1 of 1

Randomly filling a 2d array

Posted: Wed Feb 20, 2013 6:39 pm
by Oedipus
I'd like to end up with something like this
grid.png
That is, a 2d array of randomly generated "blocks", some of which are adjacent, that is randomly generated, which I'll then represent visually. It's kind of important that I use a 2d array. And I'm kind of stumped on how to fill it. Does anybody have any ideas of where to start?

Re: Randomly filling a 2d array

Posted: Wed Feb 20, 2013 10:21 pm
by magice
It looks to me like you have 1 of 4 possible values for each array element. 1 empty, 2 block, 3 x, and 4 x and block. why not a repeat loop that loops through all array elements and does a random 1 to 4 for each one.

Re: Randomly filling a 2d array

Posted: Thu Feb 21, 2013 12:07 am
by Simon
some of which are adjacent
I see there are no single (grey) blocks and no single (grey) X blocks, is that a must?

Simon

Re: Randomly filling a 2d array

Posted: Thu Feb 21, 2013 6:40 am
by dave_probertGA6e24
As Magice said - use a double repeat loop for your 2 dimensions and drops a random value into each.

Code: Select all

  repeat with x=1 to 10
    repeat with y=1 to 10
      put random(4) into myArray[x][y]
    end repeat
  end repeat


If you are doing a Battleships-type game (which is what that image reminds me of!) then you would do two runs - 1 to put some random stuff in the cells and 2 to put the long strips of the grey boxes. The boxes are not simply random cells though, but sequences representing the lengths of each 'ship'. For that you need to determine the horizontal or vertical orientation of the 'ship' and then choose a random starting point, adjust the starting point for the required length of the 'ship' and then do a loop using x or y changing values to fill the array.

Without some more detail on the randomness you require to fill the array it's a bit difficult to give any further info. If you can describe more about the purpose of the symbols then we can probably give more help.

Dave