For my upcoming Memory variation game I needed a function to generate known length Array of random numbers out of given 0-n integers Array.
For example when we call this function with this call:

result is array with 3 random numbers from range 0-10, so it can be [0, 6, 3] or [9, 3, 2] or [0, 2, 1] but numbers cannot repeat. We can also call randomArray(n, n) in which case [0, 1, ..., n] is returned, but first function parameter must be less or equal to second parameter.

Here is how function might look like, comments are for testing purposes:

If you are interested to read more about generating random stuff with ActionScript check these articles:

- Fastest Random Array Generator

- Simple Flash Snowflake Generator

- ActionScript Random Number Generator With Blur Effect

or type "random" in search box :)

*_*

**randomArray(3, 10)**result is array with 3 random numbers from range 0-10, so it can be [0, 6, 3] or [9, 3, 2] or [0, 2, 1] but numbers cannot repeat. We can also call randomArray(n, n) in which case [0, 1, ..., n] is returned, but first function parameter must be less or equal to second parameter.

Here is how function might look like, comments are for testing purposes:

```
function randomArray(number:uint, total:uint):Array {
var omega:Array = new Array();
if (number <= total) {
var alfa:Array = new Array();
var pick:uint;
var index:uint;
for (var i:uint = 0; i<total; i++) {
alfa.push(i);
}
// trace("alfa = "+alfa);
while (omega.length < number) {
index = Math.floor(Math.random()*alfa.length);
// trace("index = "+index);
pick = alfa[index];
// trace("pick = "+pick);
omega.push(pick);
// trace("omega = "+omega);
alfa.splice(index,1);
// trace("alfa = "+alfa);
}
}
return omega;
}
// function test
var om:Array = randomArray(5, 10);
trace(om);
```

If you are interested to read more about generating random stuff with ActionScript check these articles:

- Fastest Random Array Generator

- Simple Flash Snowflake Generator

- ActionScript Random Number Generator With Blur Effect

or type "random" in search box :)

*_*

## 0 comments:

Post a Comment