我试图用大块的方式洗牌,我到目前为止收效甚微。
我有一个从0到17的18个整数的数组
array = new int[18];
for(int i = 0; i < 18; i++){
array[i] = i;
}
我想要改组的每一个整数的数组
int[] chunks = {2, 3, 10, 3};
整数数组从0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17开始 当选择2的块数组的第一个元素时,选择数组的前2个元素0和1。 1移动到数组的末尾,然后是0。
现在订单是2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,0,1
对于块数组的第二个元素,它的值为3,因此选择2,3,4并将其置于0和1之上。
现在订单是5,6,7,8,9,10,11,12,13,14,15,16,17,2,3,4,0,1
这种情况一直持续到整个数组都被所有块完全洗牌
完全改组的阵列是15,16,17,5,6,7,8,9,10,11,12,13,14,2,3,4,0,1
到目前为止,我尝试编程的方法是
for(int i = 0; i < chunks[0] i++) {
int first = array[0];
System.arraycopy(array, 1, array, 0, array.length-1);
array[array.length - 1] = first;
}
这是我正在使用的代码,我得到以下结果 10,11,12,13,14,15,3,4,5,6,7,8,9,1,1,1,1,1代替 15,16,17,5,6,7,8,9,10,11,12,13,14,2,3,4,0,1
int[] array2 = array.clone();
int temp = array2[0];
int chunkIndex = 0;
int count = 0;
int chunkCount = 0;
//Loops 4 times
for(int i = 0; i < chunks.length; i++) {
//Loops as many times for the chunk element
while(chunks[i] > count) {
for(int k = 1; k < array2.length; k++) {
//Move all the elements back
array2[k-1] = array2[k];
}
chunkIndex = array2.length-1 - chunkCount;
array2[chunkIndex] = temp;
temp = array2[0];
count++;
}
//Increment the limit
chunkCount += chunks[i];
//System.out.println(chunkCount);
}
非常感谢任何帮助,如果您需要我澄清任何事情,请告诉我。
由于
答案 0 :(得分:0)
我不会给你代码,因为这是一个很好的练习。
但首先,不要再次复制数组。
基本解决方案是:
1 - Read the chunk length
2 - Save the first value in a temp variable
3 - Shift every value on the left
4 - Put the temp variable at the end
这是一种在数组中移位值的简单方法。
现在,对于每个块,您需要将值放在最后一个块之前,因此您只需要记住此块的index
在哪里。这只是lastIndex
- chunk length
。这将是转移的限制以及放置临时值的位置。
有了这个,您可以轻松编写一个能够在最佳状态下工作的解决方案。
如果块读取多个值(如果你想在12个单元格的数组中使用13个项目),则存在一些问题。
编辑:
1 - 您应该在移动数组之前保存temp
,先覆盖该值然后尝试获取它。
2 - 你总是移动整个阵列,所以你移动后会移动第一个块。这是你需要一个会减少的index
int endIndex = array2.length; //### 2 ###
while(chunks[i] > count) {
temp = array2[0]; //### 1 ###
for(int k = 1; k < endIndex; k++) { //### 2 ###
//Move all the elements back
array2[k-1] = array2[k];
}
...
}
endIndex -= chunks[i];
应该好一点,我没有时间来测试这种不幸。