【发布时间】:2016-09-04 20:13:12
【问题描述】:
例如,重复单元
1,1,1,1,1
是 1,
重复单位
1,3,2,1,3,2,1,3,2
是 1,3,2
重复单位
1,3,2,1,3,9,1,3,2
是 1,3,2,1,3,9,1,3,2
我尝试这样的想法:
1.尝试从1开始重复单元测试的次数,直到数组的大小
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]
- 如果当前测试数是重复单元,break,当前i的值为重复单元的大小
我尝试将其转换为代码:
#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 循环。有没有更简单的方法或算法来查找数组的重复单元?
【问题讨论】:
标签: c++ arrays algorithm language-agnostic