zoukankan      html  css  js  c++  java
  • iOS 生成随机数 重复 不重复

     //编程的时候,有三条任选执行路径,都会显示一些图片,比如路径1显示的图片是一个人,路径2显示的是两个人,路径3显示任意人数的图片,要求每次进入该页面都不能重复初始的那张图片。 于是我想到了 运用随机生成数来解决。 网上搜搜 果然好多方法,有一点是很重要的,随机生成,不能保证是否有重复的,那么用户体验肯定不好,为了用户果断应该选择“不重复的随机生成数的方法” 
    以下是借鉴别人的好方法 留着备用。
    
    1、获取一个随机整数范围在:[0,100)包括0,不包括100
    
    int x = arc4random() % 100;
    
    2、 获取一个随机数范围在:[500,1000),包括500,不包括1000
    
    int y = (arc4random() % 501) + 500;
    
     
    
    /***********************/
    
    //生成0~9 标记index 的数
    -(NSMutableArray *)getRandomNumber:(NSArray * )temp
    {
       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];
    }
       NSLog(@"resultArray is %@",resultArray);
       return resultArray;
    }
    
    调用:
    
    NSArray* arrary_ScrollView_Single=[[NSArray alloc]initWithObjects:@"111",@"112",@"113",@"114",@"115",@"116",@"117",@"118",@"119",nil];
    
     NSMutableArray * arrary_moment=[selfgetRandomNumber:arrary_ScrollView_Single];
    
     NSLog(@"%@",arrary_moment);
    
    resultArray is (
    
        116,
    
        114,
    
        115,
    
        117,
    
        113,
    
        118,
    
        112,
    
        111,
    
        119
    
    )
    
    //原理
    int index = arc4random() % (count - i); 
    //每取一个。减少一个。比如开始是从0~8 取一个后就少一个。
    [tempArray removeObjectAtIndex:index];
    //最重新的就是这句。它是把array 里的已取到的元素删掉,
     
  • 相关阅读:
    web服务器资源分类场景实践
    web服务器动静资源分离及负载均衡调制
    四层负载均衡
    集群中nginx服务的健康检查及负载均衡模板更新
    源码安装nginx及增加模块,nginx的秒级升级,秒级回滚
    phpadmin+redis实现图形化管理数据库笔记
    cookie和session
    移动硬盘修复工具哪个好?怎么修复教程
    硬盘 SMART 检测参数详解[转]
    磁盘显示为GPT(保护分区)
  • 原文地址:https://www.cnblogs.com/someonelikeyou/p/3631529.html
Copyright © 2011-2022 走看看