// top slide shuffle
// This is how i shuffle cards when playing a card game.
// I take a random selection from the top (10-50% of the deck) and slide it into the deck so that different parts of the top selection go into the deck at different places. In other words, I insert into the deck randomly a selection of the deck from the top.
// i named it that because i 'slide off' a portion of the top cards
// ary: the input array that will be shuffled
// howMany: the number of cards to take from the top (highest index is the top, 0 is the bottom)
function topSlideShuffle(ary, howMany){
if(howMany >= ary.length) return ary; // trying to skim too many cards, grabbed whole deck
var output = [];
var ctop = ary.splice(ary.length - howMany); // get last howMany cards in ary, also removing them from ary
// so... in real life, while you're holding the top part of the deck, the cards would remain in order. The bottom-most card of the top part wouldn't end up on top of the top-most card of the top part during the same shuffle. We'll replicate this retained order... We'll do this by grabbing howMany random indices, then incrementing them so that no 2 share the same index, then sorting them.
var rands = [];
for(var xint = 0;xint < howMany;xint++){ // get random indices
rands.push(Math.round(Math.random() * (ary.length-1)));
}
// make sure no 2 indices are the same, increment (keep it sorted)
rands.sort((a,b)=>{return a>b;}); // sort least to greatest
for(var xint = 0, len = rands.length;xint < len;xint++){
for(var yint = xint; yint < len;yint++){
if(xint == yint) continue;
if(rands[xint] == rands[yint]){
rands[yint]++;
rands.sort((a,b)=>{return a>b;});
xint--;
break;
}
}
}
// now we insert them at the randomized indices
for(var xint = 0, len = ctop.length;xint < len;xint++){
// insert the card via concat()
var deck_top = ary.splice(rands[xint]+xint); // cards above insertion index
ary = ary.concat(ctop[xint]);
ary = ary.concat(deck_top);
}
return ary;
}
function test(ary, howMany){
console.log("Top slide shuffling " + howMany + " top cards into the deck randomly. " + ary.toString() + " => " + topSlideShuffle(ary,howMany).toString());
}
test([1,2,3,4,5,6,7,8], 3);
test([1,2,3,4,5,6,7,8], 3);
test([1,2,3,4,5,6,7,8], 5);
test([1,2,3,4,5,6,7,8], 8);
Monday, April 3, 2023
Coding Challenge #40 Top Slide Shuffle - Card Shuffling
Subscribe to:
Post Comments (Atom)
Coding Challenge #54 C++ int to std::string (no stringstream or to_string())
Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...
-
I NEEDS MY JAVASCRIPT PLEASE :) Open txtcode .txt Save as .gct Please click the blue cheat code title to activate it, a...
-
Naruto Personality Quiz Please enable javascript ☯ Which Naruto Character Are You?
-
Useful for extensions that want to prevent event listeners from being attached or modify prototypes or functions, generally to defeat click...
No comments:
Post a Comment