[英]Adding and removing elements in an array: An exercise
我想用数字1到10填充数组a,并从该数组中获取一个随机数,然后将其添加到数组b中,然后从数组a中删除该元素。 我想知道最有效的方法。 编辑:(本练习要求我在数组中没有重复的值,并且每次调用该方法时排列都是随机的。)这是到目前为止的方法:
public int[] nextPermutation() {
int capOne = 10;
int capTwo = 10;
int aSize = 0;
int bSize = 0;
int[] a = new int[capOne];
int[] b = new int[capTwo];
int upperBound = 11;
Random generator = new Random();
//fill initial array with 1 - 10
for (int i = aSize; i < 10; i++) {
a[i] = i + 1;
//companion variable for sizing array
aSize++;
}
//Create a random integer and add it to array b
//Remove same integer from array a
//Repeat and remove another random integer from the remaining integers in array a and add it to b
permuted = b;
return permuted;
}
如果不是完全不正确的方式,我可能会以低效率的方式进行处理。 如果是这样,我相信您会毫不犹豫地告诉我。 在此方面的任何帮助将不胜感激。
您可以:
//randomly choose element
int index = (int) (Math.random() * aSize);
int dataFromA = a[index];
//"remove" it from A
aSize--;
for(int i = index; i<aSize; i++) {
a[i] = a[i+1];
}
//"add" it to b
b[bSize] = dataFromA;
bSize++;
唯一有趣的部分是从A中删除,您必须在循环之前减小大小(或者我可以i < aSize-1
,然后减小大小)
我猜您必须使用数组,因为这是一个练习,但是为此使用List
会更好。
这是一个使用交换产生随机排列的程序。 好吧,我不确定哪个会产生更好的结果,但是交换应该比添加/从数组中删除要快:
public int[] nextPermutation() {
int cap = 10;
int[] a = new int[cap];
Random generator = new Random();
//fill initial array with 1 - 10
for (int i = 0; i < cap; i++) {
a[i] = i + 1;
}
for (int i = 0; i < cap; i++) {
int j = generator.nextInt(cap);
int x = a[j];
a[j] = a[i];
a[i] = x;
}
// You can reduce the size of the output array:
// int output[] = new int[5];
// System.arraycopy(a, 0, output, 0, 5);
// return output;
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.