Magician's card problem

An introduction to the magician's licensing problem:

A magician pulls out a stack of playing cards, the magician takes out 13 spades, shuffles them, and turns the cards face down. Said: "I don't look at the cards, I just count them to know what each card is?" The magician said one, and turned the first card over to see that it was Ace; the magician put the Ace of Spades on the table , continue to count the remaining cards in the hand, the second time is 1, 2, put the first card under the stack of cards, turn over the second card, which is exactly the 2 of spades, and also put it on the table . The third time is 1, 2, 3. The first two cards are placed under the stack of cards, and the third card is taken out, which is exactly the 3 of spades. In this way, 13 cards are turned out in turn, and all of them are accurate. Solve: What was the original order of the cards in the magician's hand?


Look directly at the implementation code:

The magician's licensing problem is actually a Joseph problem, and it is also simulated and solved by a circular linked list.

#include <stdio.h>
#include <malloc.h>
#define LEN sizeof (LinkList) //Define the length of this type of struct node
#define cardnumber 13

typedef struct node //Define the structure
{
	int data;
	struct node *next;
}LinkList;

LinkList* create(int m) //Create a circular linked list
{
	LinkList *head,*p1,*p2;
	int i;
	head=p1=(LinkList*)malloc(LEN);
	head->data=0;
	for(i=1;i<m;i++)
	{
		p2=(LinkList*)malloc(LEN);
		p2->data=0;
		p1->next=p2;
		p1=p2;
	}
	p2->next=head;
	return head;
}


void magician(LinkList* start,int m) //The order of control cards
{
	LinkList *p;
	int j;
	int countnumber = 2;

	p = start;
	p->data = 1;
	while(1)
	{
		for (j=0;j<countnumber;j++)
		{
			p = p->next;
			if(p->data != 0) //Here, by judging whether the data in the node is enough to be 0, to determine whether the card has been issued, a very clever idea
			{
				j--;
			}
		}
		if (p->data == 0) //When data is 0, fill in the number of cards for it
		{
			p->data = countnumber;
			countnumber++;
			if (countnumber == m+1)
				break;
		}
	}
}


int main() //main function
{
	int i;
	LinkList *p;
	p = create(cardnumber);
	magician(p,cardnumber);
	for (i=0;i < cardnumber;i++)  // 打印
	{
		printf("blackheart%3d\n",p->data);
		p = p->next;
	}
	return 0;
}

operation result:


Guess you like

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