开发者

In xcode, can I make random() or arc4random choose from a set?

开发者 https://www.devze.com 2023-01-16 06:52 出处:网络
Suppose I have a list of numbers, ie. (240, 320, 640, 920) and I want to select one of these four nu开发者_如何学Gombers at random.Can I do this with random or arc4random?Yes, but you\'ll need to use

Suppose I have a list of numbers, ie. (240, 320, 640, 920) and I want to select one of these four nu开发者_如何学Gombers at random. Can I do this with random or arc4random?


Yes, but you'll need to use an array:

int numbers[4] = {240,320,640,920};
int random = numbers[(arc4random()%4)];

By the way, arc4random() is a lot better than random() because it doesn't need to be seeded.


int values[4] = {240, 320, 640, 920};
int value = values[random() % 4];


You can do it easily, not directly with random or arc4random. Store the numbers in an array and select a random number using random or arc4random in the range of 0 to length(array) - 1. Then use that number as the index of the array. And this technique will work in any place, not in just iPhone.

0

精彩评论

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