There is an array:

NSArray* array1 = [[NSArray alloc] initWithObjects:@1, @2, @3, @4]; 

Create a new one:

 NSMutableArray* array2 = [[NSMutableArray alloc] initWithCapacity:20]; 

And I want to fill it with 20 positions with elements from the first array of array1. Do I think that you can first [array2 addObjectsFromArray:array1]; and add the remaining elements via for ?

 for(int i =0; i<4; i++) { [array2 addObject:[array1 objectAtIndex:0+i]]; } 

It works, but if I exceed the number of elements in the first array (i> 4), an error occurs.

  • And how much filling should be random? There are criteria for randomness? - Mikhail Vaysman
  • No, there is no criterion. The main thing is to fill the contents of the first array. - foggie
  • Fill it with the first element of the array or any other. I think the for loop is perfect. - Mikhail Vaysman
  • Or in the for loop, randomly select the cells of the second array for each cell of the first - then you will have a random filling. - Mikhail Vaysman

1 answer 1

Try this one.

 for(int i =0; i<20; i++) { [array2 addObject:[array1 objectAtIndex:0+(i % 4)]]; } 
  • Earned, thanks! Why did% 4 help? - foggie
  • % is the operator of the remainder of the division. In this case, the remainder of the division will always be strictly less than 4 and there will be no overflow of the array. - Mikhail Vaysman
  • Thanks for the information! - foggie