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

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]

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);

Simplest way to prevent math.random form selecting the same number twice (AS3)

I have a random number variable defined as below
var rannum:Number = Math.floor(Math.random()*50+1);
Then I have a trigger that calls for a new random number everytime a button is clicked
ranbtn.addEventListener(MouseEvent.CLICK, reran);
function reran (event:MouseEvent):void
{
rannum = Math.floor(Math.random()*50+1);
}
I would like to prevent the same random number from being selected until all the numbers have been selected and then possibly start over?
I found a few threads like this one but none of them were specifically what I needed
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.Here you have an easy example with javascript.
var uniqueRandoms = [];
var numRandoms = 50;
function makeUniqueRandom() {
// refill the array if needed
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
return val;
}
I've found another option, You can declare an array of Integers:[1,2,3,4...50] and sort them randomly.
var sorted:Array = [];
for(var i:int = 0; i < 50; i++){
sorted.push(i);
}
//I'm making a copy of sorted in unsorted
var unsorted:Array = sorted.slice();
//Randomly sort
while(sorted.join() == unsorted.join()){
unsorted.sort(function (a:int, b:int):int { return Math.random() > .5 ? -1 : 1; });
}
If you get a selected num, you can add one until it is not selected.
Create a list of integers from 1 to 50.
Pick a random integer from the list and remove it.
When there are no more integers left (after 50 picks), repeat step 1.
Code:
function createRangeOfIntegers(from:int, to:int):Vector.<int> {
if (from >= to) throw new ArgumentError("Invalid arguments");
var integers:Vector.<int> = new <int>[];
for (var i:int = from; i <= to; i++) {
integers.push(i);
}
return integers;
}
function getRandomInteger(integers:Vector.<int>):int {
var index:int = Math.random() * integers.length;
var integer:int = integers.splice(index, 1)[0];
return integer;
}
Example:
// create all the possible integers
var integers:Vector.<int> = createRangeOfIntegers(1, 50);
// select a random integer
var random:int = getRandomInteger(integers);
// When you've selected all integers you can start over
if (integers.length == 0)
integers = createRangeOfIntegers(1, 50);

how to select random objects to display on a fixed position in adobe flash

I am working on a flash project and I want to select random objects from a number of objects.
For example if I have 15 objects and I want to randomly select just 4 objects and display them on the stage at fixed position.
I have searched different forums and the problems discussed on different forums are about changing the random position of objects
Note that I don't want to randomize objects position on stage I want to select random objects from multiple objects
I have no idea how to do this.
Please help me if anyone can.
The best thing is to put those objects into array, and then get random element from it.
Here is a quick example:
var objects:Array = new Array[obj1, obj2, obj3, obj4, obj5];
var random:Object = objects.splice(int(Math.random() * objects.length), 1)[0];
Have in mind that these are predefined objects - you must populate the array by yourself. Another thing is that this splices the array, which means it removes items from it.
Good luck!
Similar to Andrey Popov's answer but step by step instead of one line:
//an array of symbols
var objects:Array = new Array(red,blue,green);
//Number you need
var needed:Number = 2;
for (var i:Number = 0;i< needed;i++){
var randomPos = int(Math.random()*objects.length);
//Insert fixed position here
objects[i].x = 0;
//remove object from array
objects.splice(i,1);
}
You need some algorithm to get unique N objects from the object pool. For example try this one:
function getItemsFrom(list:Array, count:uint):Array {
var result:Array = [];
var needed:uint = count;
var available:uint = list.length;
while (result.length < count) {
if (Math.random() < needed / available) {
result.push(list[available - 1]);
needed--;
}
available--;
}
return result;
}
//Simple test, and some results are: [16,9,7,5], [14,13,10,1], etc
var test:Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
for(var i:uint = 0; i < 20; ++i){
trace(getItemsFrom(test, 4));
}
After you will get array of objects, place them where you want.
//Place items vertically at (5,5);
var startX:int = 5;
var startY:int = 5;
//Vertical padding between items
var paddingY:int = 10;
//Current Y position
var posY:int = startY;
//Ger 2 random unique items from the given collection "someListWithItems"
var itemsToPlace:Array = getItemsFrom(someListWithItems, 2);
var item:DisplayObject, i:uint, len:uint = itemsToPlace.length;
for (i; i < len; ++i) {
item = itemsToPlace[i];
item.x = startX;
item.y = posY;
//Offset current position on height of object, plus padding
posY += item.height + paddingY;
//Add item to the display list
addChild(item);
}

Loop through array, set property of each element?

Okay, very simple: there is an array containing 3 objects. Each object has a unique property called "ID" with values of either 1, 2, or 3.
One of the objects gets deleted.
The objective now is to update the ID property of each object corresponding to the new array.length value.
So for example, the object with ID of 2 got deleted. The remaining objects in the array would each have ID values of 1 and 3 respectively.
So the objective is to loop through the array and update the ID properties to 1, and 2 (instead of 1 and 3).
So I guess the question is how to write a loop to update a common property of each element in an array. Thanks.
You can use a for-loop to go through the array, as in walkietokyo's answer, or you can use a method closure:
myArray.forEach ( function ( item:*, i:int, arr:Array) : void { item.ID = i; } );
or a while-loop:
var i:int = -1;
while (++i < myArray.length) myArray[i].ID = i;
for (var i:uint = 1; i <= myArray.length; i++) {
myArray[i].ID = i;
}
General info on loops:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcf.html
var i:uint; // for speed keep out of the loop
var arrayLength = myArray.length // for speed keep out of the loop
for (i = 0; i < arrayLength; i++) {
myArray[i].ID = i;
}