Skip to content

Instantly share code, notes, and snippets.

@Tee-Stark
Created September 25, 2022 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tee-Stark/32e7ec32762628d218501ef74c23903f to your computer and use it in GitHub Desktop.
Save Tee-Stark/32e7ec32762628d218501ef74c23903f to your computer and use it in GitHub Desktop.
Algorithm to track Ace while shuffling deck of cards by splitting into two halves
function shuffleDeckAndReturnAcePosition(cardsCount, shufflesArr) {
let cards = Array.from({ length: cardsCount }, (v, i) => i + 1);
let acePosition = cards[cards.length - 1];
let mid = Math.floor(cards.length / 2);
for (let shuffle of shufflesArr) {
// split cards into two decks
let topHalf = cards.slice(0, mid);
let bottomHalf = cards.slice(mid);
// handle case for negative numbers by reversing top and bottom decks
if (shuffle < 0) {
[topHalf, bottomHalf] = [bottomHalf, topHalf];
shuffle = Math.abs(shuffle);
}
// shuffle cards
bottomDroppedCards = [];
// drop cards one by one from bottom of each halves of the deck alternating between the halves until every card on the bottom has been dropped
//
for (let j = 0; j < shuffle; j++) {
let droppedBottom = bottomHalf.pop();
bottomDroppedCards.push(droppedBottom);
}
while (bottomHalf.length > 0) {
bottomDroppedCards.push(topHalf.pop());
bottomDroppedCards.push(bottomHalf.pop());
}
cards = bottomDroppedCards.concat(topHalf);
}
// find the position of the ace
// reverse cards array
cards = cards.reverse();
acePosition = cards.indexOf(acePosition);
return acePosition;
}
console.log(shuffleDeckAndReturnAcePosition(10, [1, -2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment