How to generate without repeat value in using two random ()
I am generating random Nos to store my matrix index for row and column . That is different row and column index Nos every time not repeat. But some time same value is generating.How to rectify this problem.
This is what i written .. for example
4 * 4 Matrix. i am running with loop and storing date
int i;
for (i=0;i<6;i++)
{
Row = arc4random() % 4 ;
Column = arc4random() % 4;
CGFloat xOffset1 = (block.contentSize.width+350)+((block.contentSize.height-15)*Column);
FireBlock.positi开发者_StackOverflowon = ccp(xOffset1,Row*15);
statement 1--- store Column;
statement 2--- store Row;
}
With only 16 different combinations, I'd write all of them in an array, shuffle the array, then select from the array.
struct row_col_index {
int row;
int column;
};
/* ... */
struct row_col_index all_combinations[4*4] = {
{0, 0}, {0, 1}, {0, 2}, {0, 3},
{1, 0}, {1, 1}, {1, 2}, {1, 3},
{2, 0}, {2, 1}, {2, 2}, {2, 3},
{3, 0}, {3, 1}, {3, 2}, {3, 3},
};
shuffle(all_combinations);
for (int i = 0; i < 6; i++) {
Row = all_combinations[i].row;
Column = all_combinations[i].column;
/* ... */
}
/* ... */
You could maintain an array of booleans that keep track of which elements you've already used. For instance:
int used[16];
memset(&used, 0, sizeof(used)); // All unused to start with
for (int i = 0; i < 6; i++)
{
// Generate random number
int r = arc4random() % 16;
// Keep generating until we've found an unused element
while (used[r])
{
r= arc4random() % 16;
}
used[r] = 1; // Mark as used
row = r % 4;
col = r >> 2;
...
}
If your matrix is 4x4, you first have 16 choices of where to place the next entry. Once it's placed you have 15 choices. Once two are placed, 14 choices. Etc. You should adjust your algorithm based on this principle.
精彩评论