This is how i am generating a unique no in between 1 to 6 and getting appropriate images from the drawable folder.
Random rand = new Random();
// n = the n
For your particular use-case, this should do the trick.
Random rand = new Random();
// n = the number of images
List imgNames = new ArrayList(n);
for (int i = 0; i < n; i++) {
imgNames.add("card" + (i + 1))
}
while (!imageNames.isEmpty()) {
String imgName = imgNames.remove(rand.next(imageNames.size());
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
}
Beware that this does not scale well as n
gets large. The remove operation is O(n)
for an ArrayList
or a LinkedList
. But for n
in the hundreds or thousands, this is probably insignificant compared with loading and displaying the images.
Also, as the comments noted "unique random numbers" is a contradiction in terms. What you are after is a random permutation of the set of numbers from 1
to n
. My solution gives you this without an explicit "shuffling" step, and that's sufficient for your use-case.