丢手绢游戏

 【题目】有n(n >1)个人围成一个圈,依次给每个人一个自然数编号(1~n自加),设定一个数字m(m <= n),手绢从1开始丢,丢到m,则m退出,然后从m+1处重新数1开始,直到最后一个人退出,问n个人依次退出的编号顺序是怎样的?

【算法】

void shift_loop(int *a,int n,int m)//move the number of m to end of a array. eg(m = 3):12345---->45123
{
    int shift_count = 0;
    int *temp_ptr = NULL,temp;
    for(;shift_count < m;shift_count++)
    {
        temp_ptr = a;
        for(;temp_ptr < a + n -1; temp_ptr++)//Reverse order
        {
            temp = *temp_ptr;
            *temp_ptr = *(temp_ptr+1);
            *(temp_ptr + 1) = temp;
        }
    }
}
void CountOff( int n, int m, int out[] )//Numbering 1~n,m is mark,if someone is m then out then from next of m to begin until last one.out[] will be stored number from 1~n
{
    int index;
    int count = 0;
    int a[n];
    for(index = 0;index < n; index++)
    {
        a[index] = index + 1;//store numbering
    }
    while(count < n)
    {
        shift_loop(&a[count],n - count,m - 1);//m-1 is order to make mth element to quit.
        out[count] = a[count];
        count++;
    }
}
void CountOff_input(void)
{
    int m, n;
    puts("Enter n and m:");
    if(scanf("%d %d",&n,&m) != EOF)
    {
        int out[n];
        fflush(stdin);//clear input buffer,due to '\n' still in input buffer,because scanf will not get '\n' from input buffer.
        CountOff(n,m,out);
        for(int i = 0;i < n; i++)
        {
            printf("%d ",out[i]);
        }
        printf("\n");
    }
}

void main(void)
{
    CountOff_input();
}

yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs=wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值