尝试创建一个或两个函数,这些函数将能够检查数组的元素并输出wheater,这两个数组的元素相同(即存在相同的数字和相同的位置),或者存在存在的数字但不匹配与另一个数组相同的位置。基本上,我正在尝试重新创建一个名为mastermind的简单游戏。我遇到的主要问题是当说正确答案为[1,2,3,4]且用户将猜测[0,1,1,1]时的大小写参量,我的功能将得出数字1存在3次,我需要弄清楚如何让数字1出现1次。这是检查数组的函数:

function make_move(guess, answ){
    var myguess = document.getElementById("mymoves");

    var correct_number_correct_spot= 0;
    var correct_number_wrong_spot= 0;
    for(var i = 0; i < 4; ++i)
    {

        if(answ[i] == guess[i]){
            ++correct_number_correct_spot;
            }
        else if(answ[i] !== guess[i] && $.inArray(guess[i], answ) !== -1){
            ++correct_number_wrong_spot;
           }
        }

     console.log(answ);
        console.log(guess);


    myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";

}

最佳答案

您可以将missed个数字保留在一个对象中,然后减去答案中出现的猜测数字。然后,您可以计算出correct_number_wrong_spot减去correct_number_correct_spot的数量和缺失的数量。

function make_move(guess, answ){
    var myguess = document.getElementById("mymoves");

    var correct_number_correct_spot = 0;

    // Initialize missed counts to the numbers in the answer.
    var correct_number_wrong_spot = answ.length;
    var missed = {};
    for (var j = 0; j < answ.length; j++) {
        missed[answ[j]] = (missed[answ[j]] || 0) + 1;
    }

    for(var i = 0; i < answ.length; ++i)
    {
        if(answ[i] == guess[i]){
            ++correct_number_correct_spot;
        }
        // Subtract the guessed numbers from the missed counts.
        if (guess[i] in missed) {
            missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
        }
    }

    // Subtract the correctly spotted numbers.
    correct_number_wrong_spot -= correct_number_correct_spot;
    // Subtract the remaining missed numbers.
    for (var number in missed) {
        correct_number_wrong_spot -= missed[number];
    }

    console.log(answ);
    console.log(guess);

    myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";
}


检查demo

编辑:我试图解释注释中暴露的疑问:


  您介意解释一下这段代码的工作方式吗:for(var j = 0; j

missed[answ[j]] = (missed[answ[j]] || 0) + 1;


这是增加数字计数或将其初始化为0(如果尚不存在)的快速方法。该语句或多或少是这样的:

如果未定义missed[answ[j]],则其为falsy,因此||(或运算符)的值将为0。否则,如果我们已经有一个大于0的值,则它是truthy,并且||会得出包含的数字。

如果看起来很奇怪,则可以将以下行替换为:

if (!(answ[j] in missed)) {
    missed[answ[j]] = 0;
}
missed[answ[j]] += 1;



  同样如果(guess [i] in missed){missed [guess [i]] = Math.max(0,missed [guess [i]]-1);


missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);


在这种情况下,我使用Math.max来确保我们不减去0以下。我们不希望重复的数字超过答案计数中出现的数字。我的意思是,我们最多减去直到答案中重复数字的数量。

if (missed[guess[i]] > 0) {
    missed[guess[i]] -= 1;
}

10-08 19:55