Josephus problem solution

In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

There are people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom.

The task is to choose the place in the initial circle so that you are the last one remaining and so survive.

以上摘自Wiki,关于更多“约瑟夫问题”的细节可以参考http://en.wikipedia.org/wiki/Josephus_problem


本来想用循环链表来实现,如果只是找出最后一个获胜的人可行。但是因为需要找到能够获胜的位置,所以直接用数组实现相对简单。


#include "stdio.h"
#define LEN 40
#define K 3


int main(){
	int man[LEN] = {0};
	int n = -1;
	int winner;

	printf("the number of mans is: %d\nthe skipped number k is: %d\n", LEN, K);
	for (int i = 0; i < LEN; ++i){
		int count = 0;
		while (count <= K){
			n = (n+1)%LEN;
			if (man[n] == 0){
				++count;
			}
		}
		man[n] = i+1;
		if (i == LEN-1){
			winner = n+1;
		}
	}

	printf("the Josuphus Sort are: \n");
	for (int i = 0; i < LEN; ++i){
		printf("%d ", man[i]);
	}
	printf("\nthe winner is: %d\n", winner);
}

output:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值