iOS 隨機數 不重復


1、獲取一個隨機整數范圍在:[0,100)包括0,不包括100

int x = arc4random() % 100;

2、  獲取一個隨機數范圍在:[500,1000),包括500,不包括1000

int y = (arc4random() % 501) + 500;



/***********************/

//生成0~9
    NSArray *temp = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7", @"8",@"9",nil];
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:temp];
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    int i;
    int count = temp.count;
    NSLog(@"count:%d",count);
    for (i = 0; i < count; i ++) {
        int index = arc4random() % (count - i);
        [resultArray addObject:[tempArray objectAtIndex:index]];
        NSLog(@"index:%d,xx:%@",index,[tempArray objectAtIndex:index]);
        [tempArray removeObjectAtIndex:index];
        
    }
    [tempArray release];
    NSLog(@"resultArray is %@",resultArray);

//輸入出
    /*
    resultArray is (
                    9,
                    3,
                    1,
                    4,
                    5,
                    8,
                    7,
                    6,
                    2
                    )
*/

//原理
int index = arc4random() % (count - i); 
//每取一個。減少一個。比如開始是從0~8 取一個后就少一個。
[tempArray removeObjectAtIndex:index];
//最重新的就是這句。它是把array 里的已取到的元素刪掉,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM