Randomly filling a 2d array

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
Oedipus
Posts: 1
Joined: Wed Feb 20, 2013 6:29 pm

Randomly filling a 2d array

Post by Oedipus » Wed Feb 20, 2013 6:39 pm

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?

magice
Posts: 457
Joined: Wed Mar 18, 2009 12:57 am

Re: Randomly filling a 2d array

Post by magice » Wed Feb 20, 2013 10:21 pm

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.

Simon
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 3901
Joined: Sat Mar 24, 2007 2:54 am

Re: Randomly filling a 2d array

Post by Simon » Thu Feb 21, 2013 12:07 am

some of which are adjacent
I see there are no single (grey) blocks and no single (grey) X blocks, is that a must?

Simon
I used to be a newbie but then I learned how to spell teh correctly and now I'm a noob!

dave_probertGA6e24
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 328
Joined: Mon Dec 05, 2011 5:34 pm
Contact:

Re: Randomly filling a 2d array

Post by dave_probertGA6e24 » Thu Feb 21, 2013 6:40 am

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
Coding in the Sun - So much Fun.
Visit http://electronic-apps.info for released App information.

Post Reply