您的位置:首页 > 其它

判断一个数组是否为单一完全循环数组

2012-05-22 03:36 316 查看
判断一个数组是否为单一完全循环数组

/* Determine if an array is a single complete circle by the following rules:
* a[0]=1 -> a[1]=3 -> a[4]= 2 -> ...
* If array a is of length 6, a[6] -> a[0]
*/

using namespace std;

/*
Starting from a[0] without loss of generality, it can only return
to a[0] after traversing all data items. Anytime before that if it
goes back to a[0], this array is not a single and complete circle.
*/

bool isSingleCompleteCircle(int* x, int len)
{
int index = 0;
for (int i = 0; i < len; i++)
{
index = ((index%len) + (x[index]%len)) % len;
// to prevent overflow (not all the time, but when len is not very large)
if ((index == 0) &&(i < len-1))
{
return false;
}
}
return true;
}

int main(void)
{
int a[]={1, 1, 1, 5};
int len = sizeof(a)/sizeof(a[0]);
bool result = isSingleCompleteCircle(a, len);
cout << "A single and complete circle? " << (result?"Yes":"No") << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐