vendredi 13 septembre 2019

Trying to shuffle to generate a random number from an array and splice, but keep getting undefined for the last element that's left in the array

    <body>
        <div id="bingo">
            <script>

                let numbers = new Set()
                        .add("B1")
                        .add("B2")
                        .add("B3")
                        .add("B4")
                        .add("B5")
                        .add("B6")
                        .add("B7")
                        .add("B8")
                        .add("B9")
                        .add("B10");

                let called = Array.from(numbers);

                let display = new Array();


                function getRandomNum()
                {
                    function rando()
                    {
                        for (let i = called.length - 1; i > 0; i++) 
                        {
                            const j = Math.floor(Math.random() * called.length);
                            const number = called[i];
                            called[i] = called[j];
                            called[j] = number;

                            if(number) 
                            {
                                called.splice(j, 1);
                            }

                            if(called.length < 0)
                            {
                                return;
                            } else
                                {
                                    return number;
                                }
                        }


                    }

                    if(called.length === 0)
                    {
                        index = "No More Numbers";
                    }else
                        {
                            index = rando();
                                display.push(index);
                        }
                    document.getElementById('bingo').innerHTML = index;

                }


                function show()
                {
                    for(let n = 0; n < display.length; n++)
                    {
                        document.getElementById('reveal').innerHTML += "<br/>" + display[n] + "<br/>";
                    }
                } 



            </script>
        </div>

        <div id="button">

            <button onclick="getRandomNum()">Random Number</button>

        </div>

        <br/>
        <br/>
        <br/>

        <div id="reveal">

            <button onclick="show()">Numbers Called</button>
        </div>

    </body>
</html>

HERE, I CAN GENERATE RANDOM NUMBERS THAT DON'T REPEAT, MY ONLY ISSUE IS THAT WHEN IT GETS TO THE LAST ELEMENT OF THE ORIGINAL ARRAY, IT GENERATES "UNDEFINED" INSTEAD OF THE VALUE. NEED HELP WITH FIXING THAT PART SO THAT IT DISPLAYS "NO MORE NUMBERS" ONCE ALL THE ELEMENTS HAVE BEEN RANDOMLY GENERATED AND REMOVED




Aucun commentaire:

Enregistrer un commentaire