|
-
August 11th, 2011, 11:13 AM
#7
Re: Randomizing multidimensional vectors/arrays
Okay, so it's random rearrangement rather than random selection.
There are two primary approaches you can use:
1) Define a2 in such a way that its memory is contiguous (it is not presently), then use random_shuffle on the entire range. A boost::multi_array is one easy way to do this, or you could use a vector<int> for the underlying data and a vector<int*> to represent the rows. There's lots of material on different ways to define 2D arrays around.
2) Keep a2 as-is, but shuffle a 1D array of 2D indexes into it. For instance,
Code:
vector<pair<int,int>> inds;
inds.push_back(make_pair(0,0));
inds.push_back(make_pair(0,1));
...
inds.push_back(make_pair(3,2));
inds.push_back(make_pair(3,3));
random_shuffle(inds.begin(),inds.end());
for (unsigned i = 0; i < inds.size(); ++i)
{
unsigned row = i/4;
unsigned col = i%4;
a2[row][col] = a[inds[i].first][inds[i].second];
}
(not tested)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|