Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

练习题6:猴子选大王 #17

Open
chenhuiYj opened this issue Jun 29, 2020 · 0 comments
Open

练习题6:猴子选大王 #17

chenhuiYj opened this issue Jun 29, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

1.假设N个猴子围成一圈,从 1 开始报数,数到 M 的猴子退出。第二轮倒着数,数到 M 的猴子退出。。。以此类推,最后剩下的猴子就是大王
2.写出函数,返回当选大王的猴子的最初位置

假设参数 (n,m),输入(3,2)

就生成编号为 [0,1,2] 的三只猴子,这个编号也就是猴子的最初位置,到时候把编号返回就可以了

话说回来,输入(3,2) 生成的数组就是 [0,1,2]

比如一轮报数,编号 0 首先报 1,编号12,然后编号1的报数等于M,就是等于2,所以编号 1 要退出,所以猴子剩余 [0,2]

第二轮报数,由于倒着数,需要把猴子数组反转一下。就变成了[2,0]

然后报数,编号21,编号02,然后编号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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant