1,1,1,1,1
重复单元为1
1,3,2,1,3,2,1,3,2
重复单元是
1,3,2,1,3,9,1,3,2
1,3,2
重复单元
是1,3,2,1,3,9,1,3,2
我尝试的想法是这样的:从1重复单元测试的
1.try数,直到阵列的大小
2.仅尝试这是阵列的尺寸,例如多个编号:n
3.检查如果n是重复单元的大小,例如:假设测试重复单元为3,则检查是否
a[0]==a[3*1],a[1]==a[1+3*1],a[2]==a[2+3*1]
a[0]==a[3*2],a[1]==a[1+3*2],a[2]==a[2+3*2]
a[0]==a[3*r],a[1]==a[1+3*r],a[2]==a[2+3*r]
- 如果当前测试号是重复单元,休息一下,我的当前值是重复单元的大小
我尝试将其转换为代码:
#include <stdio.h>
int main(){
int a[]={1,3,2,1,3,2,1,3,2};
int i;
//1.try number of repeat unit test from 1,until the size of array
for(i=1;i<=sizeof(a)/sizeof(int);i++){
//2.only try number which is multiple of the size of array,e.g.: n
int n=sizeof(a)/sizeof(int);
if(n%i==0){
//3.check if n is the size of repeat unit
bool isRepeat=true;
for(int j=0;j<n;j++){
for(int r=1;r<i;r++){
if(a[j]!=a[j+r*n]){
isRepeat=false;
break;
}
}
}
//4.if the current testing number is repeat unit, break, and the current value of i is the size of repeat unit
if(isRepeat){
break;
}
}
}
//print the result using repeat unit n
for(int n=0;n<i;n++){
printf("%d ",a[n]);
}
};
,但它显示了重复单元的1,3,2,1,3,2,1,3,2是1而不是1,3,2。我认为这个解决方案的想法太复杂了,因为它有太多for循环。有更简单的方法或算法来找到数组的重复单位吗?