Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using rand() to generate a random point in a 2d matrix

Status
Not open for further replies.

raydona

Programmer
May 12, 2005
27
GB
Location Matrix::randomAdjacentLocation(Location& location)
{ int row = location.getRow();
int col = location.getCol();
.
.
}
Above ‘location’ represents an occupied point in a two-dimensional matrix. How can I use row, col and rand() to generate a (random) point that is adjacent to ‘location’? If all adjacent points to ‘location’ are occupied, how can I get the function to look further afield, that is, how can I increment row and col non-uniformly? I would be very grateful for all help.
 
Count how many adjacent locations are valid and call it n. Then assign each adjacent location a number from 0 to n-1. Then get a random number from 0 to n-1, for example with rand() % n. Whichever number you get refers to the location that was randomly picked.

If the first step yields zero unoccupied locations, then expand your search to further locations until you get a count greater than 0. How you do that depends on the rules of your application. Once you have a count greater than 0, you can move on to the next step of the algorithm above.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top