views:

91

answers:

2

Hi everyone, 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);
    }
   }
+6  A: 
Collections.shuffle(pairsX);
SingleShot
I looked to see if all your answers were neat little one liners, as I had hoped from your name. Oh well. Nicely done.
Jeremy Roberts
Thanks, SingleShot. I forgot, I have used collections.suffle before but that is for single number. Thanks :-)
Jessy
Ha ha. My name is from my online first-person shooter days :-)
SingleShot
A: 

I am just providing you the pseudo code. Say you have three items in the list.

  1. i= Generate a random number between 0 to list.size() -1
  2. j =Generate another random number similarly.
  3. 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

Kushal Paudyal