0

I would like to add an array in another array but randomly, I would like the items of my second array to mix with the items of the first array simply, how to do? I searched everywhere but no response

victor bill
  • 209
  • 2
  • 15

2 Answers2

0

This is fast and dirty, but works.

Add your two arrays together and loop through the combined array. As you do so set the item to the random key of an nsdictionary, then return the allValues part of the dictionary. Dictionaries do not keep their order anyway, but sticking random keys in seems to help it along. Alternatively, once you have the random keys in the dictionary, sort by ascending value and then output the values, might be 'more' random.

-(NSArray *)addRan:(NSMutableArray *)one combineWith:(NSArray *)two {

    //add
    [one addObjectsFromArray:two];

    //make random position
    NSMutableDictionary * ran = [NSMutableDictionary new];
    for (NSString * item in one){

        int random = arc4random_uniform((int)one.count);
        while ([ran.allKeys containsObject:@(random)]){
            random = arc4random_uniform((int)one.count);
        }
        ran[@(random)] = item;
    }

    return ran.allValues;
}

Call like this:

NSArray * ran = [self addRan:[@[@"A",@"B",@"C"] mutableCopy] combineWith:@[@"D",@"E",@"F"]];
NSLog(@"ran is %@", ran);
Johnny Rockex
  • 4,136
  • 3
  • 35
  • 55
0

I would like to add an array in another array but randomly.

Solution: To get a random element out of your second array, first count the number of elements in that array; then use the below code to get a random number.

int r = arc4random_uniform(count);

You can use that integer r to get a random element from the second array.

For mixing the elements from both arrays count the total number of elements in both the arrays and create a new NSMutableArray. Remember NSMutableArray is not a sparse array; it does not allow empty slots that can be filled in later. So what you can do is add null objects that will act as empty-slots.

NSMutableArray *mixedArray = [NSMutableArray array];
for(int i = 0; i<10; i++) {
   [mixedArray addObject: [NSNull null]];
}

You can then check if the retrieved object isEqual: [NSNull null] to know if the slot is empty or not and add your elements accordingly.

Tejas K
  • 682
  • 11
  • 28