CCode for Artists - Miles DeCoster

Creating a list of consecutive numbers and randomizing the order

We have two scripts here. The first creates an array of numbers between a starting number and ending number (in this case 1 - 52) and then randomizes the order. This could be used for any kind of card game or a random distribution of colors, etc. The second script uses the randomized list to deal out 52 cards. Refresh the page and the order changes.

<script>
// This relies on a cheap trick using the inner workings of the sort function.
// The sort function compares pairs of values in the array and rearranges them depending on the return value
// of the comparison: negative return value means the second of the pair is first, 0 value, no change,
// and positive value the first is first. Here we don't pass the sort function any values, we just
// randomize the return value given back to the sort function in each comparison so as it sorts it just makes a random order.

function makeRandomArray(min,max){
    var r= [];
    while(max>= min) r.push(max--);   
    r.sort(function(){return .5- Math.random()});  
    return r;
}
	
$(document).ready( function() {
myList=makeRandomArray(1,52);
for (var i=0; i<52; i++) {
		$('#tableTop').append("<div class='card'></div>"); 
		$('.card').eq(i).html(myList[i]); 
	}
	$('#tableTop').append("<br class='clearfloat'>"); 
	
});
</script>