Ggd Hhdhd
Ggd Hhdhd

Reputation: 145

Trying to create a shuffle function

Function works but a 53rd undefined element gets added to the array when the number of shuffles gets too high.

function shuffle(deck , shuffles) {
    for(let i = 0; i < shuffles; i++) {
     let first = Math.floor(Math.random() * 53);
     let secound = Math.floor(Math.random() * 53);
     let fShuffle = deck[first];
     let sShuffle = deck[secound];
     deck[first] = sShuffle;
     deck[secound] = fShuffle;
    }
    return deck;
  }

It shuffles everything but an undefined element sneaks in and I'm not sure how to get rid of it.

Upvotes: 0

Views: 116

Answers (2)

ScottR2020
ScottR2020

Reputation: 11

My code creates a random number and is multiplied by the length of the deck to get a specific index and then adds the value of that index to a new array.

    for (shuffled_deck.length = 0; shuffled_deck.length < 52 ; shuffled_deck) {
        // Creates a random number and multiplies it by length of deck.
        var chosencard = Math.ceil(Math.random() * numcards)
        if (chosencard == 52) {
           chosencard = 0
        }

        var addcard = totaldeck[chosencard]
        // Uses the random number to be an index in the totaldeck array 
        if (shuffled_deck.includes(addcard)) {
        }
        else {
           shuffled_deck.push(addcard) // Adds the value into the new shuffled deck array
        }
    }
    console.log(shuffled_deck)

Hope that makes sense.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

since deck will have 52 elements so your index will be from 0 to 51 in case your Math.floor(Math.random() * 53) results in 52 then you're accessing deck[52] which is undefined

you need to change it to

Math.floor( Math.random() * 52 )

Upvotes: 1

Related Questions