题
如何打乱成对中的元素?下面的程序生成所有可能的对,然后对这些对进行洗牌。例如洗牌之前可能的对是 ab,ac,ae,af
..等改组为 ac,ae,af,ab
...ETC
如何让它不仅成对地洗牌,而且在对本身的元素内洗牌?例如代替 ab, ac,
我怎样才能使 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;
}
}
解决方案
你只需要洗牌 temp
在将其添加到之前列出 pic2
. 。这是固定代码(请注意,我将 pic2
变量到一个字段 ListGenerator
类并将其重命名为 result
)
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);
public class ListGenerator {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
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);
Collections.shuffle(temp);
result.add(temp);
}
}
Collections.shuffle(result);
}
//This method return the shuffled list
public ArrayList<ArrayList<Integer>> getList() {
return result;
}
}
然而,这只是解决方案的第一步。目前,每对将包含范围内的整数 [0..size-1]
所以你的配对看起来像这样: <0,3>
, <1,2>
, , ETC。您可能想要的是获得一对由两个字母组成的字符串,例如: "ab", "dc"
, , ETC。在这个版本中我重命名了 getList()
到 getPairs()
更好地传达其含义。另外,我制作了构造函数 ListGenerator
接受一个字符数组,因此您只需使用所需的字符来调用它,如下所示:
List<String> pairs = new ListGenerator('a', 'b', 'c', 'd', 'e', 'f', 'g').getPairs();
这是 ListGenerator
它本身:
public class ListGenerator {
ArrayList<String> result = new ArrayList<String>();
public ListGenerator(char... letters) {
int size = letters.length;
// create a list of all possible combinations
for(int i = 0 ; i < size ; i++) {
for(int j = (i+1) ; j < size ; j++) {
ArrayList<Character> temp = new ArrayList<Character>();
temp.add(letters[i]);
temp.add(letters[j]);
Collections.shuffle(temp);
result.add("" + temp[0] + temp[1]);
}
}
Collections.shuffle(result);
}
//This method return the shuffled list
public ArrayList<ArrayList<Integer>> getPairs() {
return result;
}
}
其他提示
假设您有这些对象:
Red dress
Blue shirt
Pink panties
您想要对衣服的颜色和物品进行洗牌以获得如下内容:
Pink shirt
Blue panties
... etc
你怎么做呢?
其实很简单:只需将颜色和服装物品列表分别打乱,然后再次加入即可。
Red, Blue, Pink --> Pink, Blue, Red
dress, shirt, panties --> shirt, panties, dress
------------------------ pair
Pink shirt
Blue panties
Red dress
不隶属于 StackOverflow