Flash as3 array and loop and function - actionscript-3

I have an array:
var type:Array = [[[1,2,3], [1,2,3],[1,2,3]],
[[1,2,3], [1,2,3],[1,2,3]]];
Then I loop it to call the a function:
for(var i:int = 0;i<type.length;i++) {
addGrid(type[0][i]);
}
The function that I'm calling is:
public function addGrid(col,row:int, type:Array) {
var newGird:GridE = new GirdE();
newGird.col = col;
newGird.row = row;
newGird.type = type;
}
Hope it clear what i need. My Gird can be a big as the array is for the Array sample in here the Gird would be 3(Columns)x2(Rows)

ActionScript 3 multidimensional arrays may be referenced using multiple array indexes by looping your row and column.
Per your array structure, you first define rows, then columns.
This makes a lookup for cell value:
grid[row][col]
Iterating all elements could be implemented as:
private var grid:Array = [[[ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ]],
[[ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ]]];
public function loop()
{
// for every row...
for (var row:uint = 0; row < grid.length; row++)
{
// for every column...
for (var col:uint = 0; col < grid[row].length; col++)
{
// your value of "1, 2, 3" in that cell can be referenced as:
// grid[row][col][0] = 1
// grid[row][col][1] = 2
// grid[row][col][2] = 3
// to pass row, col, and the value array to addGrid function:
addGrid(row, col, grid[row][col]);
}
}
}
public function addGrid(row:int, col:int, value:Array):void
{
/* ... */
}

Related

How to add numbers in array via a loop in AS3?

var arr: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
I can add these numbers to an array separately like this but how do I add 1 to 50 at once instead of typing it all the way through?
for (var i:Number=1; i<=50;i++){
var arr:Array(i) = [i];
}
function randomize(a: * , b: * ): int {
return (Math.random() > .5) ? 1 : -1;
}
trace(arr.sort(randomize));
I am trying to implement something like this.
Thank you.
Pretty simple. You can address the Array's elements via square bracket notation. Works both ways:
// Assign 1 to 10-th element of Array A.
A[10] = 1;
// Output the 10-th element of A.
trace(A[10]);
Furthermore, you don't even need to allocate elements in advance, Flash Player will automatically adjust the length of the Array:
// Declare the Array variable.
var A:Array;
// Initialize the Array. You cannot work with Array before you initialize it.
A = new Array;
// Assign some random elements.
A[0] = 1;
A[3] = 2;
// This will create the following A = [1, null, null, 2]
So, your script is about right:
// Initialize the Array.
var arr:Array = new Array;
// Iterate from 1 to 50.
for (var i:int = 1; i <= 50; i++)
{
// Assign i as a value to the i-th element.
arr[i] = i;
}
Just keep in mind that Arrays are 0-based, so if you forget about index 0 it will remain unset (it will be null).

Array of column Letters to Array of Column Numbers not working

This is more or less my first attempt at writing a Javascript function and I want to convert an array of column numbers to an array of column letters
If I run testFunction I get undefined
function testFunction() {
var ui = SpreadsheetApp.getUi();
aryCLTCN(["A","C","D"])
ui.alert(aryCLTCN[3]);
}
function aryCLTCN(array) {
var columnLet = array
var output = [];
for (var i = 0, length = columnLet.length; i < length; i++) {
output[i] = [];
output[i] = CLTCN(columnLet[(i)]);
}
}
function CLTCN(letter)
{
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
{
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
}
return column;
}
There are several problems with your code.
Within function testFunction() you call aryCLTCN(["A","C","D"]) but don't assign the result to a variable, then with aryCLTCN[3] you are trying to access a property "3" of the function itself. Which isn't a syntax error because functions can have properties, but the function has no such property so you get undefined. You need something like this:
var result = aryCLTCN(["A","C","D"]);
ui.alert(result[3]);
Except note that JavaScript arrays are zero-based, which means that [3] tries to access the fourth element, but your array only has three elements.
Within function aryCLTCN(array) you create an output array but don't return it. You need to add return output;.
Also with these two lines:
output[i] = [];
output[i] = CLTCN(columnLet[(i)]);
...the first line assigns output[i] to a new empty array, but the second line overwrites that with the return value from CLTCN(columnLet[(i)]);. You can remove output[i] = [];.
Putting all that together:
function testFunction() {
// var ui = SpreadsheetApp.getUi(); // commented out for demo in browser
var result = aryCLTCN(["A","C","D"])
// using alert() instead of ui.alert() for demo here in browser
alert(result[3]); // undefined because there's no 4th element
alert(result[2]); // shows third element
}
function aryCLTCN(array) {
var columnLet = array
var output = [];
for (var i = 0, length = columnLet.length; i < length; i++) {
output[i] = CLTCN(columnLet[(i)]);
}
return output;
}
function CLTCN(letter)
{
var column = 0, length = letter.length;
for (var i = 0; i < length; i++)
{
column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
}
return column;
}
testFunction();
(Note that for the purposes of having a runnable code snippet in my answer I'm using alert() instead of ui.alert(), but in your real code you would stick with ui.alert().)
You get an undefined error because you are calling the trying to access an index on a function. aryCLTCN function needs to have a return the output array and you need to assign it to a variable in your testFunction to be able to access its elements.
Although there was nothing logically or effectively wrong with your functions, I have provided another working solution below.
function testFunction() {
var ui = SpreadsheetApp.getUi();
var colArr = ["A", "B", "Z", "AA", "AZ", "ZA", "AAA"];
var nColArr = colArr.map(function(col) {
var colNum = 0;
col.split('').forEach(function(l, i) { colNum += (l.charCodeAt() - 64) * Math.pow(26, col.length - 1 - i) });
return colNum;
});
ui.alert(nColArr); //Shows all elements inside the nColArr array.
ui.alert(nColArr[3]); //Shows the 4th element inside the nColArr array.
}
Try it out:
var colArr = ["A", "B", "Z", "AA", "AZ", "ZA", "AAA"];
var nColArr = colArr.map(function(col) {
var colNum = 0;
col.split('').forEach(function(l, i) {
colNum += (l.charCodeAt() - 64) * Math.pow(26, col.length - 1 - i)
});
return colNum;
});
console.log(nColArr);

As3 - Script Error on Arrays

please inspect me coding:
function createRandomList():void
{
var newlist:Array = [0,1,2];
var curlist:Array = item[selectedlevel - 1] //selectedlevel = 1;
var normal:int = curlist[0];
var tempboo1:Boolean = false;
var tempboo2:Boolean = false;
var tempboo3:Boolean = false;
while (curlist[0] + curlist[1] + curlist[2] > 0)
{
if (Number(curlist[0]) == 0 && tempboo1 == false)
{
newlist.splice(newlist.indexOf(0), 1);
tempboo1 = true;
}
if (Number(curlist[1]) == 0 && tempboo2 == false)
{
newlist.splice(newlist.indexOf(1), 1);
tempboo2 = true;
}
if (Number(curlist[2]) == 0 && tempboo3 == false)
{
newlist.splice(newlist.indexOf(2), 1);
tempboo3 = true;
}
var temp:int = Math.floor(Math.random()*(newlist.length));
curlist[temp] -= 1;
generatedlist.push(Number(newlist[temp]));
trace(item);
}
while (normal > 0)
{
var temp2:int = Math.floor(Math.random() * 3) + 1;
generatednormal.push(Number(temp2));
normal--;
}
}
My item was [[5,0,0],[10,0,0]];
But after became [[0,0,0],[0,0,0]];
I just want to duplicate Array item to be a new variable curlist.
Every time it traces, returning item[0][0] decreasing 1, I only want to use curlist as a temp Array to calculate a new random Array based on item[0].
Ouput:
4,0,0,10,0,0
3,0,0,10,0,0
2,0,0,10,0,0
1,0,0,10,0,0
0,0,0,10,0,0
Is there any links between them, or is it my problem? Please help! If you need any more infoemation, please comment me!
Arrays are passed by reference, not value. That means when you modify an array through any property that points to it, the original array will be modified.
To make a duplicate, you can use .slice()
Returns a new array that consists of a range of elements from the original array, without modifying the original array. The returned array includes the startIndex element and all elements up to, but not including, the endIndex element.
If you don't pass any parameters, the new array is a duplicate (shallow clone) of the original array.
You can clone your arrays if you want to create a new reference.
function clone( source:Object ):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject( source );
myBA.position = 0;
return( myBA.readObject() );
}
var a:Array = [[0,0],[1,1]];
var b:Array = clone(a);
b[0] = [2,2];
trace(a)
trace(b)
Output
0,0,1,1
2,2,1,1
It works for any object, not only arrays.
More infos here : AS3 - Clone an object
var array : Array = [ 1, 2, 3];
var array2 : Array = array.concnt();
array[ 0 ] = 4;
trace( array );// 1, 2, 3
trace( array 2);// 4, 2 ,3
So use .concat() to duplicate an array with primitives. If you have an arrays with arrays. Duplicate the children arrays, and put them into an empty one. If you have children of children arrays and so forth, make something recursive.

Does method already exist in ActionScript to search array and return first index whose element is > some #?

Using ActionScript 3, suppose I have an array of numbers, lets say: 1, 2, 3, 4, 5. Is there a way to easily search this array and return the index corresponding to an element that is >= 2.5 (which would be, 3, in this case), for example? I'm implementing this with a while and for loop, and seems pretty wordy. Thought there might be a method for this already, but haven't stumbled upon it in:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#every()
Otherwise, what would be a simple way to achieve it?
In case it helps, I'll use this to implement a straight-forward linear interpolation math routine, assuming one doesn't already exist I'm not aware of.
I'm not aware of any firstIndexOf in ActionScript.
You could add it to an ArrayUtil class:
Given the array:
var array:Array = [ 1, 2, 3, 4, 5 ];
Pass it to the ArrayUtil function:
public static function firstIndexOf(array:Array, value:Number):int
{
for(var i:uint = 0; i < array.length; i++)
{
if(array[i] >= value)
return i;
}
// if not found, return -1
return -1;
}
var t:Array = [4,9,1,2,3,5,6];
function something(base:Number, array:Array):int
{
var t:Array = array.slice();
var h:Number = int.MAX_VALUE;
var i:int = -1;
while(t.length > 0)
{
var l:Number = t.pop();
if(l >= base)
{
if(h > l)
{
h = l;
i = t.length;
}
}
}
return i;
}
trace(something(2, t)); // at index [3]

Cleanly merge two arrays in ActionScript (3.0)?

What's a nice way to merge two sorted arrays in ActionScript (specifically ActionScript 3.0)? The resulting array should be sorted and without duplicates.
To merge (concatenate) arrays, use .concat().
Below are two examples of how you can concatenate arrays and remove duplicates at the same time.
More convenient way: (you can use ArrayUtil.createUniqueCopy() from as3corelib)
// from as3corelib:
import com.adobe.utils.ArrayUtil;
var a1:Array = ["a", "b", "c"];
var a2:Array = ["c", "b", "x", "y"];
var c:Array = ArrayUtil.createUniqueCopy(a1.concat(a2)); // result: ["a", "b", "c", "x", "y"]
Slightly faster way: (you can loop through the arrays yourself and use Array.indexOf() to check for duplicates)
var a1:Array = ["a", "b", "c"];
var a2:Array = ["c", "b", "x", "y"];
var a3:Array = ["a", "x", "x", "y", "z"];
var c:Array = arrConcatUnique(a1, a2, a3); // result: ["a", "b", "c", "x", "y", "z"]
private function arrConcatUnique(...args):Array
{
var retArr:Array = new Array();
for each (var arg:* in args)
{
if (arg is Array)
{
for each (var value:* in arg)
{
if (retArr.indexOf(value) == -1)
retArr.push(value);
}
}
}
return retArr;
}
This is kind of an simple algorithm to write. I would be surprised if there were a more direct way to do this in Actionscript.
function merge(a1:Array, a2:Array):Array {
var result:Array = [];
var i1:int = 0, i2:int = 0;
while (i1 < a1.length && i2 < a2.length) {
if (a1[i1] < a2[i2]) {
result.push(a1[i1]);
i1++;
} else if (a2[i2] < a1[i1]) {
result.push(a2[i2]);
i2++;
} else {
result.push(a1[i1]);
i1++;
i2++;
}
}
while (i1 < a1.length) result.push(a1[i1++]);
while (i2 < a2.length) result.push(a2[i2++]);
return result;
}
Using Array.indexOf to detect duplicates is going to be painfully slow if you have a List containing a large number of elements; a far quicker way of removing duplciates would be to throw the contents of the Array into a Set after concatenating them.
// Combine the two Arrays.
const combined : Array = a.concat(b);
// Convert them to a Set; this will knock out all duplicates.
const set : Object = {}; // use a Dictionary if combined contains complex types.
const len : uint = combined.length;
for (var i : uint = 0; i < len; i++) {
set[combined[i]] = true;
}
// Extract all values from the Set to produce the final result.
const result : Array = [];
for (var prop : * in set) {
result.push[prop];
}
If your program makes heavy use of Collections then if may be prudent to make use of one of the many AS3 Collections frameworks out there which provide a simple interface for manipulating data and will always take the optimal approach when it comes to the implementation.
AS3Commons Collections
Polygonal DS
function remDuplicates(_array:Array):void{
for (var i:int = 0; i < _array.length;++i) {
var index:int = _array.indexOf(_array[i]);
if (index != -1 && index != i) {
_array.splice(i--, 1);
}
}
}
Then for the "merge" use concat.
exemple :
var testArray:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];
var testArray2:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];
testArray.concat(testArray2);
trace(testArray);
remDuplicates(testArray);
trace(testArray);
Please follow the below step to get your answer:
Concat two array using "Concat" Methos.
New Array (concated) sort using "Sort" method which provided as API in Array Class
Make user defined function to remove duplicates (see below functions)
> function removeDuplicates(p_arr:Array):Array {
var ansArr:Array = new Array();
var len:uint = p_arr.length;
var i:uint = 0;
var j:uint = 0;
ansArr[j] = p_arr[i];
i++;
j++;
while(i<len)
{
if(ansArr[j] != p_arr[i])
{
ansArr[j] = p_arr[i];
j++;
}
i++;
}
return ansArr;
}
Returned "ansArr" will be sorted and without duplicate merged array of two array.