复制并随机化列表中项目的位置

时间:2017-02-16 14:32:01

标签: java

我在java中有一个整数的Arraylist,名为list,包含7个元素[12, 13, 17, 18, 19, 11, 20]。我想用随机顺序在列表的末尾复制相同的元素两次,所以最后要有三次相同的整数(所以总共21项),然而,每7个项目随机顺序。我怎么能用Java做到这一点?

5 个答案:

答案 0 :(得分:1)

只需复制列表并对每次迭代进行随机播放。

final int DUPLICATE_AMOUNT = 3; // if you want the created array 3 times as big as the original

List<Integer> list = getMyList(); //original list 
List<Integer> fullRandom = new ArrayList<Integer>();
fullRandom.addAll(list);
for (int i = 1; i < DUPLICATE_AMOUNT; i++) {
    List<Integer> randomList = new ArrayList<Integer>();
    randomList.addAll(list);
    Collections.shuffle(randomList);
    fullRandom.addAll(randomList);
}

答案 1 :(得分:1)

只需将您的清单复制两次并将其随机播放:

List<Integer> tempList = new ArrayList<>(yourList);

for(int i = 0; i < 2; i++){
  Collections.shuffle(tempList, new Random(System.nanoTime()));
  yourList.addAll(tempList);
}

答案 2 :(得分:1)

// init your list
List<Integer> initialList = new ArrayList<Integer>();
initialList.add(new Integer(12));
initialList.add(new Integer(13));
initialList.add(new Integer(14));
initialList.add(new Integer(15));
// create a new list that'll contain your random numbers
List<Integer> tripleList = new ArrayList<Integer>();
// triple your values
tripleList.addAll(initialList); 
tripleList.addAll(initialList);
tripleList.addAll(initialList);
// randomize their order
Collections.shuffle(tripleList);
// until is empty get the top of the list with this command. 
//A random number among your list
tripleList.remove(0);

答案 3 :(得分:1)

尝试使用Collections.shuffle()并为初始数据列表调用两次:

private List<Integer> shufflePositions(List<Integer> data) {
    Collections.shuffle(data);
    return data;
}

public void solve() {
    List<Integer> data = new ArrayList<>();
    data.add(12);
    data.add(13);
    data.add(17);
    data.add(18);
    data.add(19);
    data.add(11);
    data.add(20);
    List<Integer> result = new ArrayList<>();
    result.addAll(data);
    result.addAll(shufflePositions(new ArrayList<>(data)));
    result.addAll(shufflePositions(new ArrayList<>(data)));
}

答案 4 :(得分:1)

试试这个:

List<Integer> integers = new ArrayList<>(Arrays.asList(12, 13, 17, 18, 19, 11, 20));

for(int i=0; i<2; i++) {

    List<Integer> IntegersClone = new ArrayList<>(integers);

    Collections.shuffle(IntegersClone);

    integers.addAll(IntegersClone);
}

//Output : [12, 13, 17, 18, 19, 11, 20, 19, 17, 12, 11, 20, 18, 13, 20, 12, 19, 11, 18, 13, 13, 11, 17, 18, 19, 12, 17, 20]
System.out.print(integers);