Sam B
Sam B

Reputation: 27608

List of random numbers - arc4random

I want to create an array of numbers from 0-9 and want them to be randomized

Meaning, when a user clicks on a UIButton it creates an NSMutableArray of objects 4,5,8,3,6,2,9,1,7,0

When the user clicks on the button again it generates another list of 0-9 random numbers and so on.

The problem I have is with arc4random routine. That routine will spit out a random number between 0-9 one at a time. I gotta save that number it spits out and store it into an array. I will then check to see if the next random number it spits out is already in the array or not, if not then add it in the array otherwise keep looping till it finds a number that is not in my array. Keep doing this madness till my array size is 10.

Its all well and good for a small array of 0-9. What if I needed to create a random array of lets say between 0 - 1000.

What I am looking for is an efficient method that wont take 5 years to complete. Any thoughts?

Upvotes: 0

Views: 848

Answers (2)

Sebastian Siek
Sebastian Siek

Reputation: 2075

You might want to use Random and Linq

Random random = new Random(0);
var myRandom = Enumerable.Repeat(0, n).Select(i => random.Next(0, 9));

where n is the amount of digits you want

Hope that helps

Upvotes: 0

Peter M
Peter M

Reputation: 7493

As per this SO answer whats-the-best-way-to-shuffle-an-nsmutablearray, just create your list of numbers 0..9, (or 0..1000, whatever) in a mutable array and then randomly shuffle them.

Upvotes: 3

Related Questions