简体   繁体   中英

How to create random numbers for multiple images to show randomly in Grid without repetition in iOS?

I create GridView in SpriteKit.my requirement is to shuffle images randomly in Grid View.

Here is my code to show images randomly without repetition.but this code is working for only two images.for multiple images this code is not working.

        int RandomRowMainImage          = arc4random_uniform(3);
        int RandomColumnMainImage       = arc4random_uniform(3);

        //
        int RandomRowOtherImage         = arc4random_uniform(3);
        int RandomColumnOtherImage      = arc4random_uniform(3);

        NSLog(@"RandomRowMain:%d \n Random Column :%d \n RandomRow1:%d \n randomColumn1 :%d",RandomRowMainImage,RandomColumnMainImage,RandomRowOtherImage,RandomColumnOtherImage);

        //

        BOOL checkStatus = [self checkRandomNumberColumRowLogic:RandomRowMainImage withMainRow:RandomColumnMainImage withOtherColumn:RandomColumnOtherImage withOtherRow:RandomRowOtherImage];

        if (checkStatus) {
            imgIcons.position      = [self GridPosition:MainRowCount Column:MainColumnCount];
            imgOtherImage.position = [self GridPosition:otherRowCount Column:otherColumnCount];
        }

than Code for Position of Images

//Grid Position
  -(CGPoint)GridPosition:(int)Row Column:(int)Column
 {
CGFloat offset = SizeOfGrid / 2.0 + 0.5;
CGFloat  x = Column * SizeOfGrid - (SizeOfGrid*TotalCol)/2.0 + offset;
CGFloat  y = (TotalRows-Row-1) * SizeOfGrid -(SizeOfGrid*TotalRows)/2.0 + offset;

return  CGPointMake(x, y);}

//Code to check prevent duplication of repeat random number for Two Images.

- (BOOL)checkRandomNumberColumRowLogic:(int)MainColumn withMainRow:(int)mainRow withOtherColumn:(int)otherColumn withOtherRow:(int)otherRow {

BOOL CompareRow    = false;
BOOL CompareColumn = false;

if (mainRow == otherRow) {
    int otherRow = 0;
    for (int i = 0; i < TotalCol; i++ ) {
        otherRow = [self checkRandomNumberCompare:otherRow];
        if (MainColumn == otherRow) {
            CompareRow = true;
            break;
        }
    }
    MainColumnCount = mainRow;
    otherColumnCount = otherRow;
}
else {
    CompareRow = true;
    MainRowCount = mainRow;
    otherRowCount = otherRow;
}

if (MainColumn == otherColumn) {
    int otherCol = 0;
    for (int i = 0; i < TotalCol; i++ ) {
        otherCol = [self checkRandomNumberCompare:otherColumn];
        if (MainColumn == otherCol) {
            CompareColumn = true;
            break;
        }
    }
    MainColumnCount = MainColumn;
    otherColumnCount = otherCol;
}
else {
    CompareColumn = true;
    MainColumnCount = MainColumn;
    otherColumnCount = otherColumn;
}

if(CompareRow == CompareColumn) {
    return  true;
} else  {
    return false;
}
}
-(int)checkRandomNumberCompare:(int)compareRow {
int compareDiff = arc4random_uniform(TotalRows);
return compareDiff;
}

can you please help to display multiple images without repeat? like one time one image in Node

Sorry, but the logic of your checkRandomNumberColumRowLogic: method baffles me. Given two coordinates (x1, y1) and (x2, y2) then they represent the same point if and only if x1 == x2 and y1 == y2 , and if this is not fall then they represent different points.

Here is the outline of a possible algorithm to solve your problem. First consider that given a rectangular grid of cells where the rows and columns are numbered starting from 0 then each cell can be assigned a unique number by multiplying its row index by the number of columns and adding in its column index. A diagram is worth a thousand words, given a 3 x 3 grid you get the numbering:

0 1 2
3 4 5
6 7 8

Note that given a cell number the row & column it represents can be calculated using integer division and remainder.

Doing the above reduces your problem to producing the numbers from 0 to rowCount x colCount - 1 in some random order.

There are a number of ways in which you can do this, here is one:

  1. Set upperLimit to rowCount x colCount - 1
  2. Generate a random number r between 0 and upperLimit
  3. Check if cell r is occupied, if it is add 1 to r and repeat this step
  4. Place next image into cell r
  5. Subtract 1 from upperLimit and goto step 2 if the result is greater than 0 (of course "goto" here translates to a "while" in code)

They key to avoiding duplicates is step 3, and the algorithm guarantees that step 3 will always find an unoccupied cell – proving that is left as an exercise.

HTH

I'd agree with the answer above that your logic is overly complicated. If you give an index to each image as suggested, eg for a 3x4 grid:

0  1   2 
3  4   5 
6  7   8
9  10  11

You could then randomise the grid and exchange those images. The following code would achieve this:

-(void)createRandomGridArrays
{
    NSInteger columnLength = 3;
    NSInteger rowLength = 4;

    // Create an array of NSNumbers up to the max then randomise
    NSMutableArray *indexes = [NSMutableArray new];
    for (NSInteger i=0; i<columnLength*rowLength; i++) {
        [indexes addObject:@(i)];
    }
    NSArray *randomIndexes = [self shuffleArray:indexes];
    NSLog(@"%@ -> %@", indexes, randomIndexes);    
    // (0,1,2,3,4,5,6,7,8,9,10,11) -> (1,0,6,10,4,2,7,11,9,5,8,3)

    // Convert indexes back to row/columns
    for (NSNumber *randomIndex in randomIndexes) {
        NSInteger index = [randomIndex integerValue];
        NSInteger row = index % rowLength;
        NSInteger column = index % columnLength;
        NSLog(@"%ld row:%ld, column:%ld", index, row, column);
    }
}

-(NSArray*)shuffleArray:(NSArray*)array
{
    NSMutableArray *shuffledArray = [array mutableCopy];
    for (NSInteger i=shuffledArray.count-1; i>0; i--) {
        [shuffledArray exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
    }
    return shuffledArray;
}

If you had an NSMutableArray of images you would then just exchange the image at index with the image at [randomIndexes[index] integerValue] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM