1

Even though , I execute the below code again & again I get the same Output. But , I think it should not:

int ObjectCount =500;
NSMutableArray *mut_arr = [[NSMutableArray alloc]initWithCapacity:0];
for (int i = 0; i<ObjectCount ; i++)
{    
 [mut_arr addObject:[NSNumber numberWithInt: rand()%ObjectCount]];
}
NSSet* uniqueSet = [NSSet setWithArray:mut_arr];    
NSLog(@"Array of %d objects generates %d Unique Objects",[mut_arr count],[uniqueSet count]);

The output is as follows:

Array of 500 objects generates 317 Unique Objects

Here, Since the array contains random numbers the unique set count should be same again & again for same ObjectCount.

itechnician
  • 1,645
  • 1
  • 14
  • 24
  • 2
    See here: http://stackoverflow.com/questions/3322603/how-do-i-seed-the-random-generator-and-create-a-random-int-in-objective-c – doctorlove Nov 20 '13 at 13:10

2 Answers2

3

You're not actually generating unique NSNumber objects; some of them are equal.

A NSArray can contain multiple objects that are equal. A NSSet can not. This is why the set created from your array has less objects.

The reason why you're always getting 317 objects is that you're using rand() without seeding: Why do I always get the same sequence of random numbers with rand()?

Consider using arc4random() instead, which is seeding automatically.

Community
  • 1
  • 1
Andreas Ley
  • 9,109
  • 1
  • 47
  • 57
  • Thanks.,Can you put some solid insight that why it always generates number with uniqueset value between 315 to 325 when suggested arc4random() or seed updation is used ? – itechnician Nov 20 '13 at 13:43
  • @itechnician This has to do with the probability of generating duplicate values. You're basically telling the app to give you 500 random integers between 0 and 499. Some of them are bound to be duplicates. See also: http://en.wikipedia.org/wiki/Birthday_problem – Andreas Ley Nov 20 '13 at 16:11
1

Use like this

[mut_arr addObject:[NSNumber numberWithInt:(arc4random() % (ObjectCount-1) + 1)]];
iphonic
  • 12,615
  • 7
  • 60
  • 107
  • arc4random is almost always overkill, and not needed to solve this issue. Additionally: IFF, then arc4random_uniform(u_int32_t upper_bound) should be used instead of `arc4random() % (ObjectCount-1)` – CouchDeveloper Nov 20 '13 at 13:31
  • Can you put some solid insight that why it always generates number with uniqueset value between 315 to 325 when suggested arc4random() or seed updation is used ? – itechnician Nov 20 '13 at 13:44