How to have unique random number?

后端 未结 7 798
情深已故
情深已故 2020-12-16 08:38

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         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 09:27

    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.

提交回复
热议问题