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

Nim游戏 #25

Open
Aras-ax opened this issue Apr 1, 2019 · 0 comments
Open

Nim游戏 #25

Aras-ax opened this issue Apr 1, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Apr 1, 2019

你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。

你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。

示例:

输入: 4
输出: false 
解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
     因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。

解答

function nim(num){
    return num%4 !== 0;
}

// 或
function nim(num){
    if(num <= 3 ){
        return true;
    }

    let res = [true, true, true];

    for(let i = 3; i < num; i++){
        res[i] = !(res[i-1] && res[i-2] && res[i-3]);
    }

    return res[num-1];
}
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