功能问题检查数字与阵列中存储的数字

时间:2014-01-22 12:01:27

标签: javascript

我对javaScript非常新,我正在编写一个程序来检查3个硬编码抽奖的彩票号码。我遇到的问题是,相互检查数字的功能似乎不起作用。我还希望合并一个重复的条目检查器,如果输入重复的号码,它会要求另一个号码,但不知道如何执行此操作。最后,我希望输入最大值为49,最小值为1。

问题在于,如果数字全部匹配,则输出只有1而不是6,如果没有数字匹配,则输出仍为1.

以下是代码:

<html>
<head>
    <title>Lotto Checker</title>
    <script>

        function checkerOne(drawOne, guess) {
            var i, j, count;
            count = 0;
            for (i = 0; i < 6; i++);
            {
                for (j = 0; j < 6; j++);
                {
                    if (drawOne[i] == guess[j]);
                    count++;
                }
            }
            return count;
        }
        function checkerTwo(guess, drawTwo) {
            var i, j, count;
            count = 0;
            for (i = 0; i < 6; i++);
            {
                for (j = 0; j < 6; j++);
                {
                    if (guess[i] == drawTwo[j]);
                    count++;
                }
            }
            return count;
        }
        function checkerThree(guess, drawThree) {
            var i, j, count;
            count = 0;
            for (i = 0; i < 6; i++);
            {
                for (j = 0; j < 6; j++);
                {
                    if (guess[i] == drawThree[j]);
                    count++;
                }
            }
            return count;
        }

        var date = new Date();
        var n = date.toDateString();
        var time = date.toLocaleTimeString();
        var count2;
        var drawOne = new Array();
        var drawTwo = new Array()
        var drawThree = new Array()
        var guess = new Array();
        var bonus = 45;
        var bonusGuess;
        drawOne[0] = 8
        drawOne[1] = 11
        drawOne[2] = 19
        drawOne[3] = 23
        drawOne[4] = 28
        drawOne[5] = 36


        drawTwo[0] = 2
        drawTwo[1] = 9
        drawTwo[2] = 16
        drawTwo[3] = 25
        drawTwo[4] = 39
        drawTwo[5] = 41


        drawThree[0] = 7
        drawThree[1] = 14
        drawThree[2] = 22
        drawThree[3] = 30
        drawThree[4] = 37
        drawThree[5] = 49
    </script>
</head>
<body>
    <script>
        count2 = 0;
        do {
            guess[0] = window.prompt("Enter your first number:");
            guess[1] = window.prompt("Enter your second number:");
            guess[2] = window.prompt("Enter your third number:");
            guess[3] = window.prompt("Enter your fourth number:");
            guess[4] = window.prompt("Enter your fifth number:");
            guess[5] = window.prompt("Enter your sixth number:");
            bonusGuess = window.prompt("Enter Your Bonus Ball:");
            count2++;


            document.write("The Numbers Drawn this week were: ", drawOne, " The Bonus Ball Was: ", bonus, "<br/>")
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")


            if (checkerOne(drawOne, guess) >= 5 && bonusGuess == bonus) {
                document.write("You Matched ", (checkerOne(drawOne, guess)), " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")
            }
            else if (checkerOne(drawOne, guess) >= 3)

                document.write("You Matched ", (checkerOne(drawOne, guess)), " Numbers!</br>You Have won a Prize!!</br>")

            if (checkerOne(drawOne, guess) < 3) {
                document.write("You Matched ", (checkerOne(drawOne, guess)), " Numbers! You haven't won this time!</br>")
            }
            document.write((n + ' ' + time), "</br>");
            document.write("</br>")

            document.write("The Numbers Drawn this week were: ", drawTwo, " The Bonus Ball Was: ", bonus, "<br/>");
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")



            if (checkerTwo(guess, drawTwo) >= 5 && bonusGuess == bonus) {
                document.write("You Matched ", (checkerTwo(guess, drawTwo)), " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")
            }
            else if (checkerTwo(guess, drawTwo) >= 3)

                document.write("You Matched ", (checkerTwo(guess, drawTwo)), " Numbers!</br>You Have won a Prize!!</br>")

            if (checkerTwo(guess, drawTwo) < 3) {
                document.write("You Matched ", (checkerTwo(guess, drawTwo)), " Numbers! You haven't won this time!</br>")
            }
            document.write((n + ' ' + time), "</br>");
            document.write("</br>")

            document.write("The Numbers Drawn this week were: ", drawThree, " The Bonus Ball Was: ", bonus, "<br/>");
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")
            document.write("The Number of Matches you have is: ", checkerThree(guess, drawThree), "</br>")


            if (checkerThree(guess, drawThree) >= 5 && bonusGuess == bonus) {
                document.write("You Matched ", (checkerThree(guess, drawThree)), " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")
            }
            else if (checkerThree(guess, drawThree) >= 3)

                document.write("You Matched ", (checkerThree(guess, drawThree)), " Numbers!</br>You Have won a Prize!!</br>")

            if (checkerThree(guess, drawThree) < 3) {
                document.write("You Matched ", (checkerThree(guess, drawThree)), " Numbers! You haven't won this time!</br>")
            }
            document.write((n + ' ' + time), "</br>");
            document.write("</br>")
        }
        while (guess[i] != guess[i])


    </script>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

要解决您的问题,您确实需要定义一些明确定义的函数,每个函数解决一个明确的问题 正如您的代码现在一样,存在大量冗余,这会造成混乱,耗时且容易出错 所以只是一些想法让你靠近,我没有测试代码所以仔细阅读,但你会明白:

// checks n is a valid entry
function withinBounds(n) {
    return n>=1 && n<=50 ;
}

// provides a valid lotery number
function randNumber() {
     return 1 + Math.trunc ( 50  * Math.random()  ) ;
}

// ask user for a new number to be added to currentNumbers array. 
// Check boundaries and non-redundancy.
function promptForOneNumber(currentNumbers) {
      var correctNumberReturned = false;
      var guess=0;
      while (!correctNumberReturned) {
          var message  = "Enter the number " + (currentNumbers.length + 1) + " : \n";
          if (currentNumbers.length) 
                  message     += "current numbers : " + currentNumbers.join('  ');
          guess = window.prompt( message );
          if (withinBound(guess) && (currentNumbers.indexOf(guess)<0))
              correctNumberReturned=true;
      }
     currentNumbers.push(guess);
}

// ask users for all numbers of a new board and return it.
function promptForNumbers() {
    var newGuess = [];
    // basically, call promptForOneNumber 6 times...
    for (var i=0; i<6; i++ ) promptForOneNumber(newGuess);
    return newGuess;
}

// returns the count of good results for this guess
function checkResult ( guessed, final ) {
     var matchCount = 0;
     for (var i=0 ; i< guessed.length; i++) {
         var thisGuessed = guessed[i] ;
         if (final.indexOf(thisGuessed) >= 0) matchCount++;
     }
     return matchCount;
}

function greetUser ( matchCount ) {
    // ... do a switch on matchCount

}

// ....
function createRandomBoard() {
     var newBoard = [] ;
     var newNum = 0;
     for (var i=0; i<6; i++ ) {
         do {
            newNum = randNumber();
         } while (newBoard.indexOf(newNum)>0);
         newBoard.push(newNum);
     }
}

// one attempts will go like :
var board1      = createRandomBoard ();
var userAttempt = promptForNumbers();
var score       = checkResult ( userAttempt, board1 ) ;
greetUser       ( score ) ;

答案 1 :(得分:0)

我可以看到许多让我对这段代码感到不舒服的问题。

第一种是您使用和声明测试用户猜测绘制的函数的方式。 - 你已经使用了三个功能,只需一个即可。既然你给函数两个参数,为什么不把它们作为guessArray和drawArray?

接下来是您不断重新计算代码中匹配猜测的数量。您只需存储3个数字并重复使用它们 - 3个抽奖中每个数字的匹配数。

另一个是毫无意义的do-while循环。由于guess[i] 总是等于guess[i],因此您的代码与完全省略do-while结构的代码之间没有区别。

将6号硬编码到所有3个函数中也是许多错误的来源 - 也就是说,由于数字是硬编码的,如果你决定每次抽奖的球数更少或更多,你需要记住并追踪所有参考抽奖中球数的地方的位置 - 你最好使用一个变量,只需在程序中设置一次。

你也可以宣告你的数组1-liners,而不是他们目前所采用的7。

我意识到这很大程度上与你的问题没有严格的关系,尽管它们使代码更容易理解,减少了它的数量并使其更容易调试。 因此,我已按原样拨打document.write。这不是推荐的将内容放在页面上的方法,我会让你稍后再看一下。

以下是快速编辑代码的结果。现在准确报告了匹配数。为了减少播放(测试)期间屏幕上的信息,我已经注释掉了draw2和draw3。请注意,这三个块现在更相似?你可以很容易地创建另一个作为输入的函数(a)guessArray和(b)drawArray - 你可以连续三次调用它,指定drawOne然后drawTwo,最后是drawThree。

<html>
<head>
<title>Javascript Assessment - Lotto Checker</title>
<script>
var maxElems = 6;       // number of elements in (a) the hard-coded draw and (b) the user's guess-array.

function guessChecker(drawArray, guessArray)
{
    var drawIndex, guessIndex, matchCount;
    matchCount = 0;
    for (drawIndex=0; drawIndex<maxElems; drawIndex++)
    {
        for (guessIndex=0; guessIndex<maxElems; guessIndex++)
        {
            if (drawArray[drawIndex] == guessArray[guessIndex])
                matchCount++;
        }
    }
    return matchCount;
}

var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
var count2;
var drawOne = new Array(8,11,19,23,28,36);
var drawTwo = new Array(2,9,16,26,39,41)
var drawThree = new Array(7,14,22,30,37,49)
var guess = new Array();
var bonus = 45;
var bonusGuess;

</script>

</head>
<body>
    <script>
    //  do  
    //  {
            guess[0] = window.prompt("Enter your first number:"); 
            guess[1] = window.prompt("Enter your second number:");
            guess[2] = window.prompt("Enter your third number:");
            guess[3] = window.prompt("Enter your fourth number:");
            guess[4] = window.prompt("Enter your fifth number:");
            guess[5] = window.prompt("Enter your sixth number:");
            bonusGuess = window.prompt("Enter Your Bonus Ball:");

            /*-----------------------------
            Draw 1
            ------------------------------*/
            document.write("The Numbers Drawn this week were: ", drawOne, " The Bonus Ball Was: ",bonus, "<br/>")
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")
            var drawOneMatches = guessChecker(drawOne, guess);

            if (drawOneMatches>=5 && bonusGuess == bonus)
                document.write("You Matched ", drawOneMatches, " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")

            else if (drawOneMatches>=3)
                document.write("You Matched ", drawOneMatches, " Numbers!</br>You Have won a Prize!!</br>")

            if(drawOneMatches<3)
                document.write("You Matched ", drawOneMatches, " Numbers! You haven't won this time!</br>")

            document.write((n + ' ' + time), "</br>");
            document.write("</br>")


            /*
            //-----------------------------
            // Draw 2
            //------------------------------
            document.write("The Numbers Drawn this week were: ", drawTwo, " The Bonus Ball Was: ",bonus, "<br/>");
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")
            var drawTwoMatches = guessChecker(drawTwo, guess);
            if(drawTwoMatches>=5 && bonusGuess == bonus)
                document.write("You Matched ", drawTwoMatches, " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")

            else if (drawTwoMatches>=3)
                document.write("You Matched ", (drawTwoMatches), " Numbers!</br>You Have won a Prize!!</br>")

            if(drawTwoMatches<3)
                document.write("You Matched ", (drawTwoMatches), " Numbers! You haven't won this time!</br>")

            document.write((n + ' ' + time), "</br>");
            document.write("</br>")


            //-----------------------------
            //Draw 3
            //------------------------------
            document.write("The Numbers Drawn this week were: ", drawThree, " The Bonus Ball Was: ",bonus, "<br/>");
            document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>")
            var drawThreeMatches = guessChecker(drawThree, guess);
            if(drawThreeMatches>=5 && bonusGuess == bonus)
            {
                document.write("You Matched ", (drawThreeMatches), " Numbers! You have also matched the Bonus Ball!</br>You Have won a Prize!!</br>")
            }

            else if (drawThreeMatches>=3)
                document.write("You Matched ", (drawThreeMatches), " Numbers!</br>You Have won a Prize!!</br>")

            if(drawThreeMatches)
            {
                document.write("You Matched ", (drawThreeMatches), " Numbers! You haven't won this time!</br>")
            }
*/                          
            document.write((n + ' ' + time), "</br>");
            document.write("</br>")
    //  }
    //  while (guess[i]!=guess[i])
    </script>
</body>

答案 2 :(得分:0)

很明显,当所有答案都喜欢重写它而不是发现错误时,可以对代码做很多改进。

你遇到的问题是checkerX函数中的控制结构:

for (i = 0; i < 6; i++);

迭代某些东西,但实际上并不执行代码(因为结束语句的;)。同样适用于if。实际上你的函数会递增count一次并返回它(因此你看到所有情况都是1)。

无论如何,我重写了代码更简洁,但仍然符合最初的想法:

function check(draw, guess) {
    var i, j, count;
    count = 0;
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 6; j++) {
            if (draw[i] == guess[j]) {
                count++;
            }
        }
    }
    return count;
}

// presets
var draws = [
    [8, 11, 19, 23, 28, 36],
    [2, 9, 16, 25, 39, 41],
    [7, 14, 22, 30, 37, 49]
];
var bonus = 45;

// guesses
var questions = [
    "Enter your first number:",
    "Enter your second number:",
    "Enter your third number:",
    "Enter your fourth number:",
    "Enter your fifth number:",
    "Enter your sixth number:"
];

var guess = [];
questions.forEach(function(text) {
    do {
        var entry = window.prompt(text);
    } while (guess.indexOf(entry) !== -1 || +entry < 1 || +entry > 49);
    guess.push(entry);
});

var bonusGuess = window.prompt("Enter Your Bonus Ball:");

// checking
for (var i = 0; i < draws.length; i++) {
    var matched = check(draws[i], guess);

    document.write("The Numbers Drawn this week were: ", draws[i], " The Bonus Ball Was: ", bonus, "<br/>");
    document.write("Your Numbers Are: ", guess, " Your Bonus Ball Is: ", bonusGuess, "<br/>");

    document.write("You Matched ", matched, " Numbers!");   
    if (matched >= 5 && bonusGuess == bonus) {
        document.write(" You have also matched the Bonus Ball!");
    }

    if (matched >= 3) {
        document.write("</br>You Have won a Prize!!</br>");
    } else {
        document.write(" You haven't won this time!</br>");
    }

    var date = new Date();
    document.write((date.toDateString() + ' ' + date.toLocaleTimeString()), "</br></br>");
}

DEMO:http://jsbin.com/AjUVoga/2/edit

有些注意事项:

  • 永远不要复制粘贴功能。名为checkerX的所有3个函数执行相同的代码(除了一个因某些原因而反转的参数,但它不影响结果)
  • 数组可以使用已存储的值进行初始化。这些值可以是对其他数组的引用(请参阅绘制
  • 当你为多个值做同样的事情时,要么在一个函数中重构它,要么迭代一个数组,最好是两个值!
  • 不要使用document.write(我希望这是测试代码,所以我没有触摸它,但请不要将它用于实际应用程序)
  • 不要多次计算同一件事。保存结果并使用它而不是每次需要结果时调用函数(参见检查
  • 我还重写了你的输出条件,使其更容易理解

以下代码

do {
  var entry = window.prompt(text);
} while (guess.indexOf(entry) !== -1 || +entry < 1 || +entry > 49);
guess.push(entry);

要求用户输入,直到输入符合您的条件:是唯一的,大于或等于1且小于或等于49.您可能需要添加正则表达式检查以确保它是一个数字:

|| !entry.match(/^\d{1,2}$/);