- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
一群 child 围成一圈。选择第一个 child ,他们从那个 child 开始顺时针计数,直到达到固定数字(n,在游戏开始时给出)。当计数达到 n 时,第 n 个位置的 child 被淘汰。游戏从下一个 child 开始再次继续,这个过程一直持续到剩下一个 child 。你的目标是打印剩下的 child 的位置。
For example, if there are 10 children and the fixed number n is 6, the position of the last child who remains till the last is 3.
是否有更好的编程算法来解决这个问题?
P.S. I know that we can easily do this using arrays or other data structures. I just want the best strategy, preferably a mathematical approach.
最佳答案
我认为最简单的方法仍然是写一个循环(几乎是维基百科所说的,给 Jan Dvorak 投票):
T(1) = 0
T(c) = (T(c-1)+n) mod c
或者,写成 C(没有递归):
int non_fatal_josephus(int children, int n) {
int result = 0;
for(int i=2; i<=children; i++)
result = (result + n) % i;
return result + 1; //to make it one-based
}
复现解释:
T(c) 表示“如果我们从 c 个 child 开始,哪个 child 会赢”。
T(1) = 0 因为如果我们只有 1 个 child ,她已经赢了(第一个 child ,索引 0)。
一般情况是我们总是消除第 n 个 child (索引 n-1),一旦我们消除了她,我们就从 (c-1) 个 child 开始重新计数,但是这次不是从索引 0 开始,我们从索引 n 开始。这解释了 +n:T(c-1) 假设计数从 0 开始。我们使用 +n 来移动子索引,就好像我们从索引 n 开始一样。
关于c - 谜题:谁赢得了比赛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988612/
鉴于我使用 matches!宏观 当我尝试将它与枚举一起使用时 然后它显示出意想不到的行为。 请参阅以下最小示例,playground 中也提供了该示例 pub enum Test { FIR
鉴于我使用 matches!宏观 当我尝试将它与枚举一起使用时 然后它显示出意想不到的行为。 请参阅以下最小示例,playground 中也提供了该示例 pub enum Test { FIR
我使用 pcrecpp c++ (PCRE lib) 我需要循环获取所有匹配项。我该怎么做? 例如模式: “你好” 和主题: “你好你好” 循环应该循环 3 次(因为 3 次匹配) 1 你好 2
循环赛算法在每场比赛只有团队相遇时工作正常。但是,如何在超过两支球队在同一场比赛中相遇的体育比赛或比赛中实现它。例如彩弹射击锦标赛,其中 2 到 n 个团队在 2 到 n 场比赛中相遇。仍然保持尽可能
http://ecoocs.org/contests/ecoo_2007.pdf 我正在为我所在地区即将举行的 ecoo regionals 学习,但我对这个问题感到困惑。我真的不知道从哪里开始。 它
如果有人可以帮助我使用二维数组概念而不是使用集合,那就太好了。因为我必须在这个逻辑中使用数组并获取输出。 问题: 第 1 组有四支球队,名称分别为(“A”、“B”、“C”、“D”)第 2 组有四支球队
我几乎正在尝试重新开始 JAVA 编程,只是需要一些我正在从事的小项目的指导。 差不多,我正在举办一场台球锦标赛,我希望每个玩家都能与每个玩家交手一次: 我创建了该程序( https://sconte
我遇到了这个问题,但无法想出解决方案。有一场 Frog 赛跑, Frog 有一定数量的有效跳步。它可以向前或向后移动。为了赢得比赛, Frog 必须尽可能靠近终点线,但不能越过终点线。 例子。6, 1
Closed. This question needs to be more focused。它当前不接受答案。
我正在为篮球赛季创建一个数据库。在这一点上,我保持简单,并存储表: -联盟 id[PK], name->(NBA, NCAAM, etc) -年 id[PK], league_id[FK], year
我将在当前工作的网站上创建竞赛。每个比赛都不会相同,并且可能有不同数量的输入字段,用户必须输入这些字段才能成为比赛的一部分,例如。 比赛 1 可能只需要一个名字 比赛 2 可能需要名字、姓氏和电子邮件
我正在尝试执行一个查询,该查询可以返回 5 个条件中的大多数匹配的结果。但如果只有 5 场比赛中的 5 场比赛,则优先。 为了说明我的问题,已准备好以下 SQL。 declare @tmp table
我已将所有 Json 转换器放在一个文件 JsonUtil 中,然后有一个 ConvertToJson 方法,该方法尝试转换传递给 json 的任何对象。 基本上是这样的结构: implicit va
我是一名优秀的程序员,十分优秀!