趣味算法--约瑟夫环问题

问题描述

约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依规律重复下去,直到圆桌周围的人全部出列。

问题分析

首先假设总人数n=7,从编号为2的人开始报数,即k=2,报数到3的人出列,即m=3,直到所有人出列。

C语言数组版本

因为C数组不像Java、Python等面向对象语言那样有可以直接删除数组元素的方法,这里C语言数组版本简单的将出列的人编号设为0.

 1 #include <stdio.h>
 2   
 3 int main(void)
 4 {
 5     int total;      //define total people   
 6     int out;        //define out number
 7     int start;      //define start number
 8   
 9     /* set the total, out and start number */
10     printf("Please enter the total people\n");
11     scanf("%d", &total);
12     printf("Please enter the out number\n");
13     scanf("%d", &out);
14     printf("Please enter the start position\n");
15     scanf("%d", &start);
16 
17     int people[total];        //init the people
18     int i = start - 1;      //init i for people tag
19     int count = 0;          //init count for the people out
20     int remain = total;     //init the remain number of people
21 
22     /* init josephus ring */
23     int j = 0;
24     for (j = 0; j < total; j++)
25         people[j] = j + 1;
26 
27     /* begin to solve josephus problem */
28     printf("begin to solve josephus's problem.\n");
29     /* print josephus ring */
30     for (j = 0; j < total; j++)
31         printf("%d ", people[j]);
32     printf("\n");
33 
34     while (1)
35     {
36         if(people[i] > 0)
37         {
38             count++;
39         }else
40         {
41             i++;
42             if (i == total)
43                 i = 0;
44             continue;
45         }
46 
47         if(count == out)
48         {
49             printf("The people of %d is out.\n", people[i]);
50             people[i] = 0;
51             count = 0;
52             remain--;
53         }
54 
55         i++;
56         if (i == total)
57             i = 0;
58 
59         if (remain == 0)
60             break;
61 
62     }
63 
64     printf("Josephus has solved his problem\n");
65 
66     return 0;
67 }
C 数组版

猜你喜欢

转载自www.cnblogs.com/1-6-0/p/9087802.html