Advanced version of Joseph's ring (event-oriented and "pseudo-linked list")

Joseph Ring Problem:
There are a total of n people (subscript 0~n-1) in a room, and only the last person can survive.

Kill according to the following rules:

    • everyone in a circle
    • Clockwise, the person who reports to q will be killed each time
    • Killed people will be removed from the room
    • Then re-report the number from the next person killed, continue to report q, and then clear it until there is one remaining person
    • Ask to simulate this problem.

#include<stdio.h>
#include<malloc.h>


void Joseph(int count,int doom);


void Joseph(int count,int doom){
    int alive = count; //Number of survivors;
    int curIndex = 0; //Current subscript;
    int preIndex = count -1; //Subscript of previous person;
    int index;
    int *circle = NULL;
    
    circle = (int *)malloc(sizeof(int) * count);
    for(index = 0;index < count; index++){
        circle[index] = (index + 1) % count; //initialization Linked list;
    }
    while(alive > 0){
        int num = doom % alive -1; //Directly calculate the number of people who need to move and locate the person to be out of the circle;
        for(index = 0; index < (num == -1 ? alive - 1 : num);index++){
            preIndex = curIndex;
            curIndex = circle[curIndex]; //The person is out of the circle;
            //curIndex++;
        }
        printf("%d\n",curIndex + 1);
        alive--;
        circle[preIndex] = circle[curIndex]; //The real circle operation;
        curIndex = circle[curIndex]; //Continue to the next person ;
        
    }
    free(circle);
}

int main(){
    int count;
    int doom;
    
    printf("Please enter the total number of people, the number of doom: ");
    scanf("%d%d",&count,&doom);
    Joseph(count ,doom);
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326533282&siteId=291194637