AS3 Picking a random object from an Array with certain conditions - arrays

I'm looking for the fastest way to pick a random object that has a certain condition (from an array).
In the example below I have a multidimensional array, 50 * 50 that contains objects. I want to pick a random object from that array but that object needs to have a size larger than 100.
while (object.size <= 100)
{
attempts++;
object = grid_array[Math.round(Math.random() * 49)][Math.round(Math.random() * 49)];
}
Currently I have tested this and in some instances it takes over 300+ attempts. Is there a more elegant way to do this?
Thanks,

What I would do is first filter the source array to extract only valid candidates, then return a random one (if there are any).
For example:
function getRandomObject(grid_array:Array, minSize:Number):Object {
var filtered:Array = [];
for(var i:int = 0; i < grid_array.length; i++){
var inner:Array = grid_array[i];
for(var ii:int = 0; ii < inner.length; ii++){
var object:Object = inner[ii];
if(object.size >= minSize){
filtered.push(object);
}
}
}
return filtered.length ? filtered[int(Math.random() * filtered.length)] : null;
}
// example:
var object:Object = getRandomObject(grid_array, 100);
if(object){
// do stuff with `object`
}

I asked if you need the indexes because you could do this with RegExps and the JSON Class (Flash Player 11). With this example I stored the indexes of the objects:
Create random multidimensional Array to test the function
//---I stored a variable size and the indexes inside the Object
//---Size variable will be numbers between 0 and 500
var array:Array = [];
var i;
var j;
var size:uint = 50;
var obj:Object;
for(i = 0; i < size; i++){
array[i] = [];
for(j = 0; j < size; j++){
obj = new Object();
obj.size = Math.floor(Math.random() * 500);
obj.files = i;
obj.columns = j;
array[i][j] = obj;
}
}
Method to get random Object with size property bigger than 100
//---I'll use to search the object a JSON string
var str:String = JSON.stringify(array);
//---Function to get the random Object
function getRandom():Object{
//---RegExp to search object with size between 100 and 500
var reg:RegExp = /\{[^\}]*"size":(?:10[1-9]|1[1-9]\d|[2-5]\d\d)[^\}]*\}/g;
//---Get all matches
var matches:Array = str.match(reg);
//---Return a random match converted to object
//---If no match founded the return will be null
return matches ? JSON.parse( matches[Math.floor(Math.random() * matches.length)] ) : null;
}

Related

Multiply each element from array by every element

JavaScript
I need to do this with for loop,
I want to multiply each element from array (2 * 5 * 10 * 12)
Example
var arrNum = [2,5,10,12]
var sum = 0
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * // I don't know what to do
Any ideas :) ?
I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}
First of all, you will always get result as 0 because
your starting sum condition is 0 then multiplying it by any number in the array will always give you 0.
Here is what you should do -
var sum = 1
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * sum;
}
Try something like this:
var total = 1;
for (var i = 0; i < arrNum.length; i++) {
total *= arrNum[i];
}
var result = [2,5,10,12].reduce(function(a,b){return a*b;});
I think your question needs more explaining, I suppose you're in JS environment.
Notice the advanced funtions of ES6; I suggest to get in deep of all these advanced operations.
Please notice that under the hood the operation will be exact a for-loop, but the reduce hides the complexity and leave everything cleaner.
put the first element of the array in sum
then multiply sum * array of i which start at 1 since we put first element in sum and then put the result back in the sum
var arrNum = [2,5,10,12]
var sum = arrNum[0]
for(var i = 1; i < arrNum.length; i++) {
sum = sum * arrNum[i];
}
console.log(sum);
I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}
it works, but var sum is not a real 0 ...

can I check a regular expression on one array element?

I am trying to test if a specific element in an array is a range of characters, from a-z lowercase. what am I doing wrong? I am very new to coding (1 month in) and I am probably trying to do stuff thats too hard for me.
var array ["a","b","c"];
var myRegularExpression = /[a-z]/;
if (myRegularExpression.test(array[index])) {
//do stuff
}
To give you a working example as #Tushar mentioned:
var arr = ["a","b","c","123"];
var myRegularExpression = new RegExp("^[a-z]+$");
var matchCount = 0;
for (var index = 0; index < arr.length; index++) {
if (myRegularExpression.test(arr[index])) {
//do stuff
matchCount += 1;
}
}
document.getElementById("result").innerText = matchCount;
Number of elements matching the regex "^[a-z]+$":
<div id="result"></div>

Adding a fixed number of unique items to an array using a for loop and indexOf

I'm using a for loop to get 6 random numbers between 1-20, using indexOf to omit duplicates, and pushing them to an array.
However, I always want 6 items in the array, so I'd like duplicates to be replaced. In my naive code duplicates are simply omitted, which means that sometimes I'll get less than 6 in the array. How do I replace the omissions to fill those 6 array slots?
function rolld(event:MouseEvent) {
for (i = 0; i < 6; i++){
d = (Math.floor(Math.random() * (1 + d_hi - d_lo)) + d_lo);
if (rollArray.indexOf(d) < 0){
rollArray.push(d);
}
}
trace (rollArray);
}
Still very new to this. Thanks for any help!
When you get an element from array with 20 elements, try to remove it from array.
function rolld(event:MouseEvent) {
var elements:Array = [];
for (var i:int = 1; i <= 20; i++)
{
elements.push(i);
}
for (i = 0; i < 6; i++){
d = (Math.floor(Math.random() * elements.length);
rollArray.push(d);
//remove the element
elements.splice(d, 1);
}
trace (rollArray);
}

Two Dimension Array with Custom Type Elements

I'm trying to create on my scene an n x n size matrix, each element should be a Movie Clip, named Table, already prepared in the Library.
var tables:Array.<Table> = new Array.<Table>(tablesDimension, tablesDimension);
for (var i:int = 0; i < tablesDimension; i++) {
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables.push(tempTable);
trace(tables[0][0].x);
}
}
A Movie Clip (in this case, Table) cannot be put in two dimensional arrays? Should I use some type conversion in my last line, at the trace(tables[0][0].x); to suggest to the compiler: it's about a Table type object?
The error message I receive: "Type parameters with non-parameterized type"
I'm not sure why you're trying to do with your first line but it's incorrect.
To quote the adobe actionscript reference:
The Array() constructor function can be used in three ways.
See this adobe reference link on Array creation. Or you can use Vectors (which are typed, like you seem to want to have).
So basically you want to create an Array, that will itself contain arrays. You need to create the arrays contained in it when you go through the first one. Else you will try to push into non existing elements. Also, you need to add the index as RST said.
var tables:Array.<Table> = new Array();
for (var i:int = 0; i < tablesDimension; i++) {
tables[i] = new Array();
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables[i].push(tempTable);
}
}
trace(tables[0][0].x);
This should work.
I think you are missing an index. Try this
for (var i:int = 0; i < tablesDimension; i++) {
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables[i].push(tempTable);
trace(tables[0][0].x);
}
}

as3 random array - randomize array - actionscript 3

How do you randomize an array using actionscript 3?
There is a short version using Array.sort() function:
var arr : Array = [0,1,2,3,4,5,6,7,8,9];
function randomize ( a : *, b : * ) : int {
return ( Math.random() > .5 ) ? 1 : -1;
}
trace( arr.sort( randomize ) );
If you don't get "enough" randomness you can sort twice :)
EDIT - explanation line by line:
For Array class method sort() you can pass not only sort options like Array.CASEINSENSITIVE, Array.DESCENDING and so on but also your own custom compare function reference (a callback) that accepts two parameters (two elements from array to compare). From AS3 documentation:
A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:
A negative return value specifies that A appears before B in the sorted sequence.
A return value of 0 specifies that A and B have the same sort order.
A positive return value specifies that A appears after B in the sorted sequence.
Note: compare function parameters might be typed (if your array is typed) and have any name you want eg.:
function compareElements ( elementA : SomeClass, elementB : SomeClass ) : int;
This method is very useful when you need to sort array elements by their special properties. In randomization case compareFunction randomly returns -1, 0 or 1 and makes array elements to switch their places (indices). I have found that better randomization (in my subjective and mathematically untested opinion) is when method returns only -1 and 1. Also have in mind that sorting function with custom compare function doesn't compare elements sequentially so in some special cases randomization results may differ from what you might expect.
There's a better way that will also allow you to randomize the array in place, if you need that, and it will not make you create more then a single copy of your original array.
package
{
import flash.display.Sprite;
public class RandomizeArrayExample extends Sprite
{
public function RandomizeArrayExample()
{
super();
testDistribution();
}
private function testDistribution():void
{
var hash:Object = { };
var tester:Array = [1, 2, 3, 4];
var key:String;
for (var i:int; i < 1e5; i++)
{
randomize(tester);
key = tester.join("");
if (key in hash) hash[key]++;
else hash[key] = 1;
}
for (var p:String in hash) trace(p, "=>", hash[p]);
}
private function randomize(array:Array):Array
{
var temp:Object;
var tempOffset:int;
for (var i:int = array.length - 1; i >= 0; i--)
{
tempOffset = Math.random() * i;
temp = array[i];
array[i] = array[tempOffset];
array[tempOffset] = temp;
}
return array;
}
}
}
I had an alternative requirement where i wanted to randomly insert lots of source arrays into a target array randomly. Like Rytis i'm a big fan of the forEach, map and sort functions on Arrays.
var randomInsert:Function = function callback(item:*, index:int, array:Vector.<MyItem>):void
{
var j:Number = Math.floor(Math.random() * targetArray.length);
targetArray.splice(j,0,item);
}
targetArray = new Vector.<MyItem>();
sourceArray1.forEach(randomInsert, this);
sourceArray2.forEach(randomInsert, this);
here's an easier function. Works also on multidimensional arrays
function randomizeArray(array:Array):Array
{
var newArray:Array = new Array();
while (array.length > 0)
{
var mn=Math.floor(Math.random()*array.length)
newArray[newArray.length]=array[mn]
array.splice(mn,1)
}
return newArray;
}
I found this very helpful. I hope it can help you too.
// Array to Randomize
var firstArray:Array = ["One","Two","Three","Four","Five","six","seven","eight","nine","ten"];
trace(firstArray); // Prints in order
var newArray:Array = new Array();
function randomizeArray(array:Array):Array
{
var newArray:Array = new Array();
while (array.length > 0)
{
newArray.push(array.splice(Math.floor(Math.random()*array.length), 1));
}
return newArray;
}
var randomArray:Array = randomizeArray(firstArray);
trace(randomArray); // Prints out randomized :)
If you need your array to be shuffled (your elements can not repeat). You could use this function:
/**
* Shuffles array into new array with no repeating elements. Simple swap algorithm is used.
*/
public function shuffleArray(original:Array):Array
{
// How many swaps we will do
// Increase this number for better results (more shuffled array, but slower performance)
const runs:int = original.length * 3;
var shuffled:Array = new Array(original.length);
var i:int;
var a:int;
var b:int;
var temp:Object;
// Copy original array to shuffled
for(i=0; i<shuffled.length; i++){
shuffled[i] = original[i];
}
// Run random swap cycle 'runs' times
for(i=0; i<runs; i++){
// There is a chance that array element will swap with itself,
// and there is always small probability it will make your shuffle
// results not that good, hence try to experiment with
// different runs count as stated above
a = Math.floor(Math.random() * original.length);
b = Math.floor(Math.random() * original.length);
// Swap messages
temp = shuffled[a];
shuffled[a] = shuffled[b];
shuffled[b] = temp;
}
return shuffled;
}
Usage:
var testArray:Array = ["Water", "Fire", "Air", "Earth"];
trace(shuffleArray(testArray).concat());
this is how I randomize my array of 36 cards for a memory game
const QUANT_CARTAS: int = 36;
//get the 36 numbers into the array
for (var i: int = 0; i < QUANT_CARTAS; i++)
{
cartas.push(i);
}
//shuffles them =)
for (var moeda: int = QUANT_CARTAS - 1; moeda > 0; moeda--)
{
var pos: int = Math.floor(Math.random() * moeda);
var carta: int = cartas[moeda];
cartas[moeda] = cartas[pos];
cartas[pos] = carta;
}
// and add them using the random order...
for (i = 0; i < QUANT_CARTAS; i++)
{
var novaCarta: Carta = new Carta();
novaCarta.tipoCarta = cartas[i];
etcetcetc.............
}
choose random string from array
function keyGenerator(len:Number):String
{
function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
var hexArray = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
var key = "";
for (var i=0; i<len; i++)
{
key += hexArray[randomRange(0,hexArray.length-1)];
}
return key;
}
usage:
trace(keyGenerator(16));

Resources