0

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?

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Sam B
  • 27,273
  • 15
  • 84
  • 121
  • 2
    Sounds like you just need a [shuffle algorithm](http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray) – Joe Feb 08 '12 at 14:44
  • Sounds like a homework assignment. – bbarnhart Feb 08 '12 at 14:53
  • Not a home assignment. I am trying to create an app that shows certain pop-up text but I dont want to repeat the same text over and over. So I thought what better way to ensure uniqueness than to create an array that never repeats the same number. Hence the question. – Sam B Feb 08 '12 at 15:20

2 Answers2

3

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.

Community
  • 1
  • 1
Peter M
  • 7,309
  • 3
  • 50
  • 91
0

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

Sebastian Siek
  • 2,045
  • 17
  • 16