iOS随机算法,概率算法

ios中三种随机算法(0到10中随机取一个数字不包括5)

   //第一种

srand((unsigned)time(0)); //不加这句每次产生的随机数不变 

  int k = rand() % 10;


    //第二种

    srandom(time(0));

    int j = random() % 10;


    //第三种

    int w = arc4random() % 10 ;

//不从0开始取值的做法,三种方法原理一样

//获取一个随机数范围在:[50,100),包括50,不包括100

  int y = (arc4random() % 50) + 50;

概率算法:

现在有一个数组:

NSArray *arr = [NSArray arrayWithObjects:@"aa",@"bb",@"cc",@"dd",@"ee", nil];我要从这个数组中随机取出一个字符,但是我要求取到aa的概率是50%,cc20%,其他的都是10%;这里我们还是采用随机数来实现,取0-100的随机数,然后分成一个个你的小区间,0-49,50-59,60-79,80-89,90-99,废话不多说直接上代码:

NSArray *arr = [NSArray arrayWithObjects:@"aa",@"bb",@"cc",@"dd",@"ee", nil];

    NSInteger dd=0;//用来统计dd出现的次数(我的结果为47次)

    for (NSInteger i=0; i<100; i++) {

        int index = arc4random() % 100;

        if (index<50) {

            index = 0;

            dd++;

        }else if (index>=50&&index<60){

            index = 1;

        }else if (index>=60&&index<80){

            index = 2;

        }else if (index>=80&&index<90){

            index = 3;

        }else if (index>=90){

            index = 4;

        }

        NSString *str = arr[index];

        NSLog(@"%@",str);

    }

    NSLog(@"dd出现了%ld次",dd);

以上为自己总结,如有不当之处还请指正

你可能感兴趣的:(iOS随机算法,概率算法)