Randomize Array

2011-02-08

In some situations, you may want a function that scrambles the order of an array, regardless of what type of data it contains. In some programming languages, there are built in functions, while in others you have to solve it yourself. I believe that for example, Javascript has a ready-made function for this but I have chosen to illustrate my solution in Javascript.

My proposed solution involves creating a new, empty array in which you want to save the mixed values. Then randomize a number that is between 0 and the size of the array to be mixed. The element on the randomized position is added to of end of the new array. After that, the element is removed from the original array so it don’t need to be processed further. Now the process is repeated and you select a new, randomly selected element from the remaining elements of the original array. When the original array is empty, then all elements is stored in the new array in a scrambled order.

If you want to leave the original array untouched you should send the array as a copy rather then sending it as a reference. If you send it as a reference, the function may alter the contents of the original array. I fixed that problem in the following Javascript-code, but the problem may differ between programming languages.

<script type="text/javascript">
function randomize_array(input_array){
	//Creates a new empty array.
	var output_array = new Array();

	//Continue as long as there are elements left in input_array.
	while(input_array.length > 0){

		//Gets the position to a randomly chosen element in input_array.
		var index = Math.floor(Math.random() * input_array.length);

		//Adding the randomly chosen element to output_array.
		output_array.push(input_array[index]);

		//Removes the randomly chosen element from input_array.
		input_array.splice(index, 1);
	}

	return output_array;
}

window.onload=function(){
	//Creates a new array of values.
	var start_array = [1, 2, 3, 4, 5, 6];

	//Creates an array that receives the result from the function randomize_array. The function slice () is used on start_array to send it as a copy and not a reference. If passed as areference, the function will modify the contents of start_array.
	var end_array = randomize_array(start_array.slice());

	//Displays the contents of the arrays before and after their order has been mixed.
	alert("Start: "+start_array.join(" ")+"\nEnd: "+end_array.join(" "));
}
</script>

I have also seen another method for randomizing arrays that was written in Perl, where you instead chose a random position in the new array, seeing if it was empty, and moved the first element from the original array to the position in the new. It also worked fine when I tested it but it seems ineffective on a larger amount of elements where much of the time could be spent on randomizing positions that are already occupied.