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 number of images, that start at idx 1
rndInt = rand.nextInt(6) + 1;
String imgName = "card" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
What i want is, I have to call this method 7 times, and each time this method should return a unique random no. so that none of the already chosen numbers will come up again.
Use a linear congruential generator with appropriately chosen parameters.
Here is an example class which creates a random permutation using the approach Dan Dyer suggested. It ensures that each .next() calls gives a new number up to the number given in the constructor. After that it wraps around and gives the same sequence again. This can be useful for shuffling a playlist.
Btw. do not use the approach Snake used. It is not only because it will freeze once all numbers have been used. That can be fixed. The problem is more that the procedure runs slower and slower as more and more numbers are in the listIdontWantAnymore. With just 6 numbers it's not a problem, but it can cause quite a significant slowdown if the range is large. Consider choosing between 10000 numbers. After 9900 numbers have been chosen there is a 1% chance of hitting a good number. after 9990 numbers there is a 0.1% chance of hitting a good number and etc.
Here is an example of how you can use the class:
Create a static list of possibilities you've already gotten.
For your particular use-case, this should do the trick.
Beware that this does not scale well as
n
gets large. The remove operation isO(n)
for anArrayList
or aLinkedList
. But forn
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
ton
. My solution gives you this without an explicit "shuffling" step, and that's sufficient for your use-case.Generate a list of numbers containing every number you will use. (Which is fine, given that we are talking about a small range, where "N" is "somewhere less than a thousand")
When you choose a number, select a random index between 0 and sizeof(list), that number becomes the index of that list.
Delete that list index and return the number.
(It is an exercise to the reader to determine what kind of "list" is appropriate here.)
Here's the easiest code to do it and store into an array without any repetition:
this will create unique numbers in the array