练习题6:猴子选大王
Nobody has claimed this yet.
- Dominant language
- HTML
- Stars
- 6
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
1.假设N个猴子围成一圈,从 1 开始报数,数到 M 的猴子退出。第二轮倒着数,数到 M 的猴子退出。。。以此类推,最后剩下的猴子就是大王
2.写出函数,返回当选大王的猴子的最初位置
假设参数 (n,m),输入(3,2)
就生成编号为 [0,1,2] 的三只猴子,这个编号也就是猴子的最初位置,到时候把编号返回就可以了
话说回来,输入(3,2) 生成的数组就是 [0,1,2]
比如一轮报数,编号 0 首先报 1,编号1 报2,然后编号1的报数等于M,就是等于2,所以编号 1 要退出,所以猴子剩余 [0,2]。
第二轮报数,由于倒着数,需要把猴子数组反转一下。就变成了[2,0]
然后报数,编号2报1,编号0报2,然后编号0退出,此时猴子只剩下编号2,那么编号2的猴子就是大王。然后编号2,就是 2 就是当选大王的最初位置。把 2 返回就好
function handle(n,m){
let arr=[...Array.from({length:n}).keys()]
let _index=0
while(arr.length>1){
_index=m%arr.length
_index=_index?_index:arr.length
arr.splice(_index-1,1)
arr=arr.reverse()
}
return arr[0]
}
handle(3,4) //2
handle(5,9) //0
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's handle(n, m) example and review the supplied JavaScript implementation. Check the stated cases, including handle(3, 4) and handle(5, 9), and consider the alternating counting direction and returned original position. Done means the function produces the documented winning indices.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- content
- Issue type
- Feature
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100