我正在尝试编写一个置换数组的函数。
但是,只要offset
大于零,其中一个元素就不会被替换A[i]
,我只剩下默认的初始化值。我似乎无法弄清楚问题出在哪里。代码中的fill
andprint
函数只是用随机元素填充数组并打印数组的函数。
#include <iostream>
#include "print.h"
#include "random.h"
#include <memory>
int* permute_by_cycle(int A[], int size)
{
int dest;
int* C = new int[size];
int last = size - 1;
int offset = random(0, last);
std::cout << "offset = " << offset << std::endl;
for(int i = 0; i < size; i++) {
dest = i + offset;
//std::cout << "dest = " << dest << "\tlast = " << last << std::endl;
if(dest > last)
dest -= last;
C[dest] = A[i];
}
return C;
}
int main()
{
int size = 18;
int A[size];
//int* B = new int[size];
fill(A,size);
print(A,size);
int* B = permute_by_cycle(A, size);
print(B,size);
delete [] B;
return 0;
}
输出:
41 65 31 41 19 15 72 11 78 69 37 23 29 63 75 4 5 49
offset = 16
0 31 41 19 15 72 11 78 69 37 23 29 63 75 4 5 49 65