Josephus problem Beginner (using arrays)

Source: Internet
Author: User
Tags arrays printf

Problem Description:

This is a very classic problem, a table of people to eat together, for example, there are 6 people, the first person from 1, the number of people reported in turn, and when the number of reported for a certain number, count the person out, the game continues. Those who have not yet been out of the exit continue to count back from 1 until all the people have been out. Draw out the order of exit.

For example, there are 6 people, respectively, 1,2,3,4,5,6. When a person is out of the 3, the exit order should be: 3, 6, 4, 2, 5, 1

Solution:

You can take a logarithmic set of flag bits to resolve and set it to 0 to indicate that it is out, and you do not need to increment the count when traversing to it. It is also a common way of thinking in the actual development of the place sign.

Code:

#include <stdio.h>/*total People number*/#define ALL/*people leave when count to left_counter*/#define Left

_counter 3/*people array*/int people[all];
	/*init people array*/Void Initpeople () {int i = 0;
	for (i = 0; i < all; i++) {people[i] = i+1;
	}}/*print people array*/void Printpeople () {int i = 0;
	for (i = 0; i < all; i++) {printf ("%d", people[i]);
} printf ("\ n");
	} int main (void) {initpeople ();		int left = ALL;	/*init Total left number*/int counter = 0;		/*init counter*/int i = 0;
		/*init array index*/while (1) {if (0! = People[i]) {counter++; 
		  }/*if counter = = Left_counter, peopler out, set people[i] = 0 counter = 0;
		left--;
			**/if (counter = = Left_counter) {left--;
			printf ("%d is out\n", people[i]);
			Counter = 0;
			People[i] = 0;
		Printpeople ();
			}/*if No people left, problem solved*/if (0 = = left) {printf ("Problem finished!\n");
		Break }/*increase index*/i++;
		if (i = = All) {i = 0;
}} return 0;
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.