Shuffle Algorithm

In this example below you will see how to do a Shuffle Algorithm with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Corpheus91, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Corpheus91 ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/Corpheus91/shuffle-algorithm-jwRaYj */
    


/*Downloaded from https://www.codeseek.co/Corpheus91/shuffle-algorithm-jwRaYj */
    let deck = [];
console.log("empty deck",deck);

const generateItems = function(deckIn,size){
  for(let i=1; i<=size; i+=1){
    deckIn.push(i);
  }
  return deckIn;
}

deck = generateItems(deck,52);
console.log("Init deck",deck);

const shuffle = function(deckIn){
  console.log("Pre shuffle",deckIn);
  for(let i=0; i<deckIn.length; i+=1){
    let tempItem = deckIn[i];
    let swapIndex = Math.floor(Math.random() * deckIn.length);
    
    deckIn[i] = deckIn[swapIndex];
    deckIn[swapIndex] = tempItem;
  }
  console.log("Post shuffle",deckIn);
}

shuffle(deck);

const checkShuffle = function(deckIn){
  for(let i=0; i<deckIn.length; i+=1){
    if(deckIn[deckIn.indexOf(deckIn[i])] === deckIn[i] && deckIn.indexOf(deckIn[i]) !== i){
       console.log("Duplicate found:",deckIn[i],"at index",i);
    }
  }
}

checkShuffle(deck);

Comments