# Help needed with a card shuffling function

**URL:** <https://forum.kirupa.com/t/help-needed-with-a-card-shuffling-function/257994>\
**Category:** programming\
**Created:** [April 19, 2008, 9:40am UTC](https://forum.kirupa.com/t/help-needed-with-a-card-shuffling-function/257994 "2008-04-19T09:40:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bolshoi333](https://avatars.discourse-cdn.com/v4/letter/b/c4cdca/32.png) [@Bolshoi333](https://forum.kirupa.com/u/Bolshoi333)\
**Post date:** [April 19, 2008, 9:40am UTC](https://forum.kirupa.com/t/help-needed-with-a-card-shuffling-function/257994/1 "2008-04-19T09:40:56Z")

</div>

Hello all! I’m trying to make a game that makes primary use of a deck of cards, but right now I’m having trouble making the deck random. My attempted method is to pop or shift (based on a random roll) the contents of array1 into array2 and back for a total of about 5 swaps ultimately ending with a nicely randomized array1 in array1. I’ve tried a couple different methods, but it always ends up a direct copy of array1 in array2.

> function shuffle(){  
> for(i=0; i\<=5; i++){  
> if(i/2 % 0){  
> swap = 1  
> }else{  
> swap = 2  
> }  
> if(swap=1){  
> while(array1.length \> 0){  
> num = random(2);  
> if(num=0){  
> array2[array2.length] = array1.pop();  
> }else if(num=1){  
> array2[array2.length] = array1.shift();  
> }  
> }  
> }else if(swap=2){  
> while(array2.length \> 0){  
> num = random(2);  
> if(num=0){  
> array1[array1.length] = array2.pop();  
> }else if(num=1){  
> array1[array1.length] = array2.shift();  
> }  
> }  
> }  
> }  
> }

If anyone could tell me how to fix this code, or even better a more efficient way to write a shuffle function, I’d be greatly appreciative. Please do excuse the mess, this is my first attempt at a real program.
