How to randomly rearrange a list of Strings and select one element at a time without repeating the value contained in the list?

Asked

Viewed 32 times

1

I am developing an application in Android studio in Java language and need to know how to solve my problem.

I have a list of String:

List<String> valores = new ArrayList<>();

Then I create a loop for to add Strings to that List. Example:

int i;
for (i = 0; i < n; i++){
    valores.add(disp[i]);
}

Continuing the reasoning, let’s say at the end of this loop for my list went like this and in that order:

"Pear" (in heading 0),
"Apple" (in heading 1) ,
"Grape" (in heading 2),
"banana" (in heading 3) and
"Pineapple" (in heading 4)

What I need is to randomly rearrange the positions of the items in my List and create a method that takes each item at once without the same value being repeated.

For example: I reorganized the positions and my List stayed that way:

"Grape" (in heading 0),
"Banana" (in heading 1),
"Pineapple" (in heading 2),
"Apple" (in heading 3) and
"Pear" (in heading 4)

Now, as an example, imagine that I have a button and when I click this button, it shows me the first position that is in the "Grape" case and that when I click the button again it shows me the second option that is banana.

My real intention was to use Collections.shuffle(valores) to shuffle the list and then use some method indicating which items in my list have already been shown.

This is all because I want to use the firebase database Realtime to make the following situation:

I have 3 users logged in. Then I send a message to the first user with a question. If the first user replies "yes" the loop will stop and my application will indicate to me that it has accepted and if it says no, then that user is dropped and the message is sent to the second and so on. Until someone says yes or everyone says no.

1 answer

0

Good evening, to shuffle the list you can create an extension to List<> as:

private static Random rng = new Random();  

public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}
// USAR
List<Product> products = GetProducts();
products.Shuffle();

To know which items you have already shown create another list and add the elements to it when you click the button, then you can check if this element has already been shown with method visualizados.conteins(KEY).

  • Thank you my friend.... I’ll do it that way!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.