我有一个伪代码,我已经翻译成java代码,但任何时候我运行代码,我得到一个空arraylist作为结果,但它应该给我一个随机的整数列表。 这里是伪代码:伪代码:随机排列
Algorithm 1. RandPerm(N)
Input: Number of cities N
1) Let P = list of length N, (|P|=N) where pi=i
2) Let T = an empty list
3) While |P| > 0
4) Let i = UI(1,|P|)
5) Add pi to the end of T
6) Delete the ith element (pi) from P
7) End While
Output: Random tour T
下面是Java代码:
public static ArrayList<Integer> RandPerm(int n)
{
ArrayList<Integer> P = new ArrayList<>(n);
ArrayList<Integer> T = new ArrayList<>();
int i;
while(P.size() > 0)
{
i = CS2004.UI(1, P.size());// generate random numbers between 1 and the size of P
T.add(P.get(i));
P.remove(P.get(i));
}
return T;
}
我不知道我做错了。
从你的代码中,'P'总是空的,你永远不会添加任何东西。还要注意,你传递的'n'是初始容量,但列表的大小是'0'。 – Berger
while循环从不执行,因为P开始空。通过给它“n”,你只是在它的后备阵列中分配了那么多的初始空间。 – satnam