开发者

arc4random except some numbers

开发者 https://www.devze.com 2022-12-21 04:32 出处:网络
How can you disallow some nubers from being chosen with the arc4random function? Current code: int random = (arc4random() % 92);

How can you disallow some nubers from being chosen with the arc4random function?

Current code:

int random = (arc4random() % 92);

(numbers from 0开发者_如何学Go to 92)

I want it do disallow the following numbers: 31, 70, 91, 92


First, you'll need to change

% 92

to

% 93

to get numbers from 0..92

I'd do something like this

int random;

do {
    random = arc4random() % 93;
}
while ( random == 31 || random == 70 || random == 91 || random == 92 );


If you are going to disallow numbers 91 and 92, why bother including them in your mod?

Expanding on the previous answer:

int random;
do {
    random = arc4random() % 91;
}
while ( random == 31 || random == 70 );


Simple, keep asking for numbers:

get a new random number
while the new number is one of the disallowed ones:
    get a new random number
return the random number

Pseudo code, but you should get the idea.


Solution for Swift:

func randomValue(except: Int) -> Int {
    var rand: Int = 0;

    repeat {
        rand = Int(arc4random_uniform(3) + 1)
    }
    while(rand == except)

    return Int(rand)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号