-2

I want to take 4 random numbers and save it into an NSSet ( to ensure that same number is not in the array)

As the int values has to be NSNumber object and hence cannot compare, it is not able to save unique integer in array.

+(NSMutableSet *)uniquenumber
{
    int j=0;
    NSMutableSet *sets=[[NSMutableSet alloc]init];
    while (sets.count<4) {
        j=arc4random()%7;
        [sets addObject:[NSNumber numberWithInteger:j]];
    }
    return sets;
}

I want to get 4 unique number randomly from 0-7. Thats the problem.

Appreciate your help and suggestions to improve the code.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
alin
  • 9
  • 1
  • 3

2 Answers2

3

As @Marc Mosby recommend, i edited my answer:

Updated Answer:

int j = 0;
NSMutableSet *set= [NSMutableSet set];

while (set.count < 4) {
    j = arc4random_uniform(7);
    [set addObject:@(j)];
}

NSArray *array = set.allObjects;
Marc
  • 6,051
  • 5
  • 26
  • 56
Mutawe
  • 6,464
  • 3
  • 47
  • 90
  • 1
    Because your answer is waaay too complicated. You basically implement an NSSet (so just use NSSet) and never use default methods (your inner for loop could be replaced with array contains:). Also the best answer would be "use your existing code because it works". (btw I did not downvote you, but I can understand the one who did it) – Marc Oct 29 '13 at 09:03
  • as a part of the question ,"it is not able to save unique integer in array", i did that to solve the NSArray unique integer problem !!! – Mutawe Oct 29 '13 at 09:24
  • Then: Use the original solution and do: `NSArray *array = [set allObjects]` – Marc Oct 29 '13 at 09:28
  • Thanks for the advice, as my answer was accepted, i had to modify it considering your recommendations – Mutawe Oct 29 '13 at 09:36
  • thanks marc mosby for ur valuable answers. – alin Oct 29 '13 at 11:33
1

This code is fine. NSNumber won't be added to NSMutableSet if equal value already exists there. Look here if not sure: NSMutableSet contains Duplicates

Community
  • 1
  • 1
Maciej Oczko
  • 1,225
  • 8
  • 11