简体   繁体   中英

How do I generate random string array urls without repeating?

I am trying to generate random string array urls in picasso, everything is working fine but it repeats, like i had 28 string array items when i start app some items are repeating but i want only 1 item at one time when random start

This is my code

     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random(); 
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);

try the following

ImageView imageView = itemView.findViewById(R.id.imageview);
Random random = new Random();
List<Integer> cache = new ArrayList<>();
int p = 0;
do {
     p = random.nextInt(icons.length);
} while(cache.contains(p));
cache.add(p);

Picasso.get().load(icons[p]).into(imageView);

You can keep track of previously generated integers in an array/list and check the array each time you generate a new random number. This way, if the new integer generated already exists in the array, you generate a new one, until you have generated 28 numbers, after which you will have to clear the array and start over.

ImageView imageView = itemView.findViewById(R.id.imageview);
Random random = new Random();
List<Integer> prevInts = new ArrayList<>();
Picasso.get().load(icons[randomUniqueInteger()]).into(imageView);

public int randomUniqueInteger(){
    int p = 0;
    do {
        p = random.nextInt(icons.length);
    } while(prevInts.contains(p));

    if ((prevInts.size + 1) == icons.length){
       prevInts.clear();
    }

    prevInts.add(p);

    return p;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM