数组列表:排列如何打印10个列表

时间:2016-01-28 08:30:33

标签: java arrays arraylist permutation

所以我应该创建一个看起来像这样的Permutation列表

输出:

Final ouput

我似乎无法让我的代码重复10次(编辑:它告诉我 numbers.add(og.get(randPick));; 超出范围,因为它变成负数

代码:

import java.util.ArrayList;
import java.util.Random;
public class ArrayListTest
{


    public void Arrays(){
        ArrayList<Integer> og = new ArrayList<Integer>();

        Random random = new Random();
        //what is inside the Array (Digits 1-10) 
        for (int x = 1; x <= 10; x++) {
            og.add(x);   
        }

        ArrayList<Integer> numbers = new ArrayList<Integer>();
        //printing 
        int a = 1; 
        while(a < 10){
            System.out.print("List " + a + ":");
            a++;
            for(int y = 0; y < 10; y++){
                //the random number itself 
                int randPick = random.nextInt(og.size());

                //adding the new random number to the permutation
                numbers.add(og.get(randPick));

                //taking out the random number slot chosen 
                og.remove(randPick);

                //printing out the current numbers in one line
                System.out.print(numbers.get(y) + " ");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

og.remove(randPick);将清除第一次while次迭代的原始列表。 在下一次迭代中,您可能会遇到异常。

另外,请参阅this question了解现成的解决方案:

java.util.Collections.shuffle(List);