Counting game (C language)

1. Topic description

Given a circle, randomly select the first person from the circle, and start counting clockwise from him, the person who counts to 3 will exit the circle, and the people behind will start counting from 1, and continue to count in order Count clockwise, and the person who counts to 3 exits the circle...until there is only one person left in the circle. Ask what the original number of the last person left is.

2. Algorithm ideas

1. First use dynamic memory allocation to apply for an int array circle with a size of n to simulate the original circle. The subscript of the array represents the number of each person, such as circle[0] represents person number 1.

2. Use a pointer p to point to circle[0], which means counting from the first person.

3. Create a loop and exit the loop when there is only one person left in the circle. In the loop, whenever someone exits the circle, mark his position with -1, use a counter cnt to count the number, when cnt=3, mark the position of the person pointed by the current pointer with -1, and set the counter set to 0.

4. After each loop, judge whether the number of people marked -1 in the circle is n-1, and if so, jump out of the loop. Finally, the position in the circle whose mark is not -1 is the position of the person left behind, and its corresponding number is output.

5. Release dynamic memory.

3. Code implementation

#include <stdio.h>
#include <stdlib.h>

int main()
{
    
    
    int n, i, cnt = 0;
    printf("请输入n的值:");
    scanf("%d", &n);

    // 动态内存分配申请一个大小为n的int型数组,模拟圆圈
    int* circle = (int*)malloc(n * sizeof(int));
    for (i = 0; i < n; i++)
    {
    
    
        circle[i] = i + 1; // 初始化圆圈中的每个人的编号
    }

    int* p = circle; // 从第一个人开始报数,指针p指向circle[0]

    while (1)
    {
    
    
        if (*p != -1) // 如果当前位置的人没有被退出圈子,那么就开始报数
        {
    
    
            cnt++; // 报数+1
        }
        if (cnt == 3) // 如果报数为3,那么退出圈子
        {
    
    
            *p = -1; // 退出圈子,将此位置用-1标记
            cnt = 0; // 计数器清零
        }

        if (p - circle == n - 1) // 如果已经到了圈子的末尾,那么就回到开头
        {
    
    
            p = circle;
        }
        else
        {
    
    
            p++; // 指针后移,指向下一个人
        }

        int out_count = 0; // 统计已经退出圈子的人数
        for (i = 0; i < n; i++)
        {
    
    
            if (circle[i] == -1)
            {
    
    
                out_count++;
            }
        }
        if (out_count == n - 1) // 如果圆圈中只剩下一个人,那么就退出循环
        {
    
    
            break;
        }
    }

    for (i = 0; i < n; i++)
    {
    
    
        if (circle[i] != -1) // 找到圆圈中最后剩下的那个人的编号
        {
    
    
            printf("最后留下的是原来的第%d号的那位\n", circle[i]);
            break;
        }
    }

    free(circle); // 释放动态内存
    return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/ikun10001/article/details/130511285