AS3 random array generator

A snippet of actionscript 3 code to create random arrays.
The allowTwins boolean, when set to false, will prevent multiple occurrences of a number in your array.

internal function createRandomArray (newArray:Array, nrElements:int, scopeRandom:int, allowTwins:Boolean) {
			newArray = new Array();
			createNr ();
			function createNr () {
				while (newArray.length < nrElements) {
					var i:int = Math.floor(Math.random() * scopeRandom);
					if (!allowTwins) {
						checkNr (i);
					} else {
						newArray.push (i);
					}
				}
			}
			function checkNr (mynum:int) {
				if (newArray.indexOf(mynum) < 0) {
					newArray.push (mynum);
				} else {
					createNr ();
				}
			}
			return (newArray);
		}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>