سؤال

I have an array of 30 images. My requirement is to fetch only 20 images every time, randomly, out of that 30 images. Each and every time fetch new 20 images.

Could anyone tell me how can I achieve this?

I tried this:

randIdx=arc4random()%[FrontsCards count];

but I get all 30. How can I get 20 images from a 30 image array?

هل كانت مفيدة؟

المحلول

Trivial approach: mutableCopy the array of images, loop from 0 to 20, select an image (idx = arc4random_uniform(copiedArray.count);) then remove the selected image from the dupe array.

(And no, don't use arc4random() % array.count, modulus makes the randomness disappear, that's why there's the arc4random_uniform() function.)

نصائح أخرى

  1. shuffle the array every time before fetching
  2. fetch the top 20 images from the array.

Have a look at different shuffling algorithm.

Just use first 20 images out of all 30 and check firstly if any image is already presented in your array wouldn't be added again in the array. For this you try a loop which will run only 20 times.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top