Display pairs in Random order
Question
How can I randomised the order of pairs? e.g. I have 3 elements stored in list e.g. A,B,C --> which makes pairs of A-B, A-C, B-C.
How can I display the pair in Random order? e.g. A-B, A-C, B-C or B-C, A-B, A-C or A-C, A-B,B-C
ArrayList<String> s = new ArrayList<String>();
s.add("A");
s.add("B");
s.add("C");
ListGenerator lg = new ListGenerator(s);
OTHER CLASS
public class ListGenerator {
private ArrayList<String> pairsX= new ArrayList<String>();
public ListGenerator(ArrayList<String> list) {
int size = list.size();
int count_pairs = 0;
// create a list of all possible combinations
for(int i = 0 ; i < size ; i++)
{
String s1 = ""+i;
for(int j = (i+1) ; j < size ; j++)
{
count_pairs++;
String s2 = ""+j;
pairsX.add(s1+","+s2);
}
}
System.out.println("numPairs "+count_pairs);
for(String s : pairsX) {
System.out.println(s);
}
}
Solution
Collections.shuffle(pairsX);
OTHER TIPS
I am just providing you the pseudo code. Say you have three items in the list.
- i= Generate a random number between 0 to list.size() -1
- j =Generate another random number similarly.
- Then print list.get(i)+"-"+list.get(j)
You can do this in a loop and add conditions to verify if the pair thus generated is a duplicate one.
I am assuming you know how to generate a random number between certain numbers..
You can do something like (Math.random() * 1000)%3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow