1

Hi I am picking objects from one array and adding it into another. Using the below method

I am doing this in a for loop.

 FirstArray = [@"object1",@"object2",@"object3",@"object4",@"object5"];
 SecondArray = [@"abc",@"pqr",@"xyz",@"123"];

NSUInteger FirstArrayIndex = arc4random() % [FirstArray count];
NSUInteger SecondArrayIndex = arc4random() % [SecondArray count];


[mainArray addObject:[FirstArray objectAtIndex:FirstArrayIndex]];
[mainArray addObject:[SecondArray objectAtIndex:SecondArrayIndex]];

But when I am using this - some times the objects will get duplicated in mainArray. How to prevent this ? Without saving the index, is there any other method to achieve this ?

3 Answers3

2

Check if it exists in the destination array before adding it:

 MyArray = [@"object1",@"object2",@"object3",@"object4",@"object5"];
 for (NSUInteger i = 0; i < 3; i++) {    // Assuming you are adding 3 objects
    NSUInteger RandomIndex;
    do {
        RandomIndex = arc4random() % [MyArray count];
    } while ([mainArray indexOfObject:[MyArray objectAtIndex:RandomIndex]] == NSNotFound)
    [mainArray addObject:[MyArray objectAtIndex:RandomIndex]];
}
Droppy
  • 9,691
  • 1
  • 20
  • 27
  • Thanks for the answer - I edited my question please check that and suggest a solution –  Aug 05 '14 at 15:44
0

If you are just trying to randomize the array you use this method which this answer provides https://stackoverflow.com/a/56656/1916721:

NSUInteger count = [MyArray count];
for (NSUInteger i = 0; i < count; ++i) {
    NSInteger remainingCount = count - i;
    NSInteger exchangeIndex = i + arc4random_uniform(remainingCount);
    [MyArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}

You could then just pull elements one by one out of the shuffled array or copy it entirely.

The alternative would be to just check if it already exists, otherwise find another random index.

Community
  • 1
  • 1
carloabelli
  • 4,289
  • 3
  • 43
  • 70
  • Thanks for the answer - I edited my question please check that and suggest a solution – –  Aug 05 '14 at 15:45
  • You could add both arrays to a temp `NSSet` (duplicates will not be added). Then convert the set back into an array and shuffle it. This might help http://stackoverflow.com/a/3966974/1916721 – carloabelli Aug 05 '14 at 15:52
0

You should remove the object that you are selecting from the initial array so that you do not pick it again.

Wyetro
  • 8,439
  • 9
  • 46
  • 64