How to shuffle the elements in the pairs?
The program below, generate all possible pairs and later shuffle the pairs.
e.g. possible pairs before shuffle is ab,ac,ae,af..etc shuffled to ac,ae,af,ab…etc
How to make it not only shuffled in pairs but within the elements in the pair itself?
e.g. instead of ab, ac, how can I make ba, ac ?
String[] pictureFile = {"a.jpg","b.jpg","c.jpg","d.jpg","e.jpg","f.jpg","g.jpg"};
List <String> pic1= Arrays.asList(pictureFile);
...
ListGenerator pic2= new ListGenerator(pic1);
ArrayList<ArrayList<Integer>> pic2= new ArrayList<ArrayList<Integer>>();
public class ListGenerator {
public ListGenerator(List<String> pic1) {
int size = pic1.size();
// create a list of all possible combinations
for(int i = 0 ; i < size ; i++) {
for(int j = (i+1) ; j < size ; j++) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(i);
temp.add(j);
pic2.add(temp);
}
}
Collections.shuffle(pic2);
}
//This method return the shuffled list
public ArrayList<ArrayList<Integer>> getList() {
return pic2;
}
}
You just have to shuffle the
templist before you add it topic2. Here’s the fixed code (note that I turned thepic2variable into a field of theListGeneratorclass and renamed it toresult)However this is just the first step towards a solution. Currently, each pair will contain integers in the range
[0..size-1]so your pairs look like this:<0,3>,<1,2>, etc. What you probably want is to get a pairs that are two-letter String such as:"ab", "dc", etc. In this version I renamedgetList()togetPairs()which convey its meaning better. Also, I made the constructor ofListGeneratoraccept an array of characters so you just need to call it with your desired characters, as follows:And here is
ListGeneratorit self: