flash as3 using an array inside of Math.max() function [duplicate] - arrays

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the best way to get the minimum or maximum value from an Array of numbers?
Hi - I'm trying to use flash's Math.max() functionality to find the highest of a set of numbers. Normally, these are input via a comma delimited string of numbers, but I need to have it loop through a series of numbers in an array. What is the proper syntax for this? I tried:
var maxMemberWidth = int(Math.max(
for (var k=0;k<memberClips.length;k++){
memberClips[i].memeberWidth;
}
));
but that's obviously not right. I have a feeling the answer involves running some sort of separate function and returning the values to this function, but I haven't quite gotten the syntax right yet.

Your aproach is not ALL wrong, you can do this:
// note the apply in the next line!
var maxMemberWidth:int = int(Math.max.apply(null, AllMembersWidth()));
...
private function AllMembersWidth():Array
{
var widths:Array = [];
for (var k:int = 0; k < memberClips.length; k++)
widths[k] = memberClips[k].memeberWidth;
return widths;
}
This works even when you have an empty array (it returns -Infinity)

You can try this instead:
var max_number:Number = memberClips[0];
for( var i:int = 1; i < memberClips.length; i++ )
{
max_number = Math.max( max_number, memberClips[i] );
}
What this does is initializes the maximum number to the first element of your array and then loops through all the elements in your array until it reaches the end of the array. You'll then have the maximum number you're seeking. The index variable i is initialized to 1 because you don't need to compare the first element against itself. You should take note that this code also assumes that you have at least one element in your array.

More condensed version, not as sexy looking as it would be on ruby but it works.
var widths:Array = clips.map( function(o:*, i:int, a:Array):* { return o.width; } );
var max:Number = Math.max.apply(null, widths);
var min:Number = Math.min.apply(null, widths);

Related

Code is not executing the else condition in the inner most loop when matching array to array index by index?

var amazon = activeSpreadsheet.getSheetByName('Amazon');
var lastRow1 = amazon.getLastRow();
var array1 = amazon.getRange('A2:A' + lastRow1).getValues();
var source = activeSpreadsheet.getSheetByName('ProductDetails');
var lastRow2 = source.getLastRow();
var array2 = source.getRange('B2:B' + lastRow2).getValues();
n = 2;
x = 0; // match
z = 0; // non-match
for (var i = 0; i < array2.length; i++){
for (var j = 0; j < array1.length; j++){
if (array2[i] !== array1[j]){
z = z + 1;
}
else {
x = 9999
}
}
newsheet.getRange([n],[5]).setValue(z);
newsheet.getRange([n],[6]).setValue(x);
if (z > x) {
newsheet.getRange([n],[1]).setValue(array2[i]);
n == n++;
z = 0;
x = 0;
}
else if (z < x) {
z = 0;
x = 0;
}
}
My project is written in GAS (google app scripts) which is essentially, for all intents and purposes JS with variation in libraries.
Basically I am grabbing an element in the array2 and passing it through a loop to match to array1. For every time it does not match it adds 1, and when it matches (should only match once if it has any matches) it stores an arbitrary large number (larger than length of array1) and compares them.
As you can see I've written out to display these values and I always get z = 5183 (length of array1) and x = 0 (meaning no non-matches found). Therefore even if something exists in array 2 and 1 it will always write it to the cell.
What should happen is if there is a match, z= 5182 and x= 9999 (or arbitrary large number) and since 5182 < 9999 it doesn't do anything.
Is my scope wrong? Or am I not writing the If/Else correctly? Or is it something else?
Your code performs a strict comparison between the elements of two Arrays. That's fine, in general. However, for those specific Arrays those elements are also Arrays, which means strict (in)equality is checking to see if those are the exact same array object in memory. See this question for more information.
You probably wanted to do a value-based comparison, which means you need to compare the specific element of that inner array (i.e., index again). if (array2[i][0] !== array1[j][0]) {...} will check the 1st element of the inner array.
Looking at the instantiation of array1 and array2, we see that these are indeed 2D arrays from a single-column Ranges, so there will be only 1 element in each inner array. You can reduce the level of indexing necessary by flattening these arrays when you read them:
const array1 = sheet.getRange(...).getValues().map(function (row) { return row[0]; });
const array2 = ...;
I'm also not sure why you are passing in arrays to Sheet#getRange - you should pass in 1-4 arguments in manners consistent with the method signatures detailed in the Apps Script documentation.
Note that there are much better algorithms for checking if a value exists in a given array - you re-scan all of the 2nd array for every value of the first array. You should conduct thorough research into this topic before asking a new question on how to improve your algorithm.
Lastly, you should implement the best practice of using batch methods - you currently call setValue in a loop. Consider storing the results to write in an array, and then writing with Range#setValues once your loop has completed. There are many questions available for you to review on this topic.

Printing Array Items by Index Number in ImageJ (Fiji)

I'm trying to figure out how I can access an item in an array by it's index number. I've written a script which will generate an array, with some number of variables. There's an old script on the imageJ mailing list archive (shown below) which is able to print given index value for a known value within the array, but is there a way to find the value within the array itself? I.e. if I have the user input the number of values that should be in the array, can I have the macro call up the values in the array from that?
My array generator:
Dialog.create("Time Point Input");
Dialog.addNumber("How many time points?", 0)
Dialog.addString("What are your time points (comma separated, no spaces)?:",0);
Dialog.show();
time = Dialog.getNumber();
points = Dialog.getString();
Fpoints = newArray(points);
Where the readouts could be something like:
time = 4
points = 5,10,12,27
Fpoints[0] = 5
Fpoints [1] = 10
Fpoints [2] = 12
Fpoints [3] = 27
Calling up index from array number value example code:
arr = newArray(1,5,3,12);
i = index(arr, 5);
print("index = "+i);
function index(a, value) {
for (i=0; i<a.length; i++)
if (a[i]==value) return i;
return -1;
}
Thank you!
I am not 100% sure if I get your question right.
but is there a way to find the value within the array itself?
The problem is that you cannot create an Array with points since it's a String.
Try something linke:
Fpoints = split(points, ',');
Then you can iterate over Fpoints with a loop, or use you index function to get an index of a given value.
for (i = 0; i < Fpoints.length; i++) {
print(Fpoints[i]);
}

Fisher-Yates Shuffle Algorithm error

so I'm currently making a quiz game with Actionscript 3.0, and I wanna shuffle the questions with this Fisher-Yates Shuffle Algorithm:
This is my code:
var questions:Array = [1,2,3,4,5,6,7,8,9,10];
function ShuffleArray(input:Array)
{
for (var i:int=input.length-1; i>=0; i--)
{
var randomIndex:int = Math.floor(Math.random() * (i+1));
var itemAtIndex:int = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
}
function buttoncorrect(event:MouseEvent):void
{
ShuffleArray(questions);
trace (questions);
var quest:int = questions.splice(questions, 1)[0];
trace(quest);
}
btntry.addEventListener(MouseEvent.CLICK,buttoncorrect);
And here is the trace result:
9,7,5,10,4,8,6,2,1,3
9
7,1,2,6,8,10,5,4,3
7
5,2,3,10,6,1,8,4
5
4,3,10,6,2,8,1
4
2,1,8,3,6,10
2
10,8,6,1,3
10
3,8,6,1
3
1,8,6
1
6,8
6
8
0
Why do I always get the "0" value at the end? I should've get the value of "8" right?
Does someone know what's wrong with my code? Thank you.
The problem is this line:
var quest:int = questions.splice(questions, 1)[0];
The first parameter to splice() is supposed to be a start index. Since you want to remove the first element, it should be zero:
var quest:int = questions.splice(0, 1)[0];
The reason your code works for each case except the last one is because of the way automatic type conversion from Array to int works. ActionScript is automatically converting the array passed as the first parameter to a zero when it has more than one element, but converts it to the value of the only element in the array when it has a single element. So it is effectively:
var quest:int = questions.splice(0, 1)[0];
right up until the last call, when you pass in an array containing the single value 8. Then the last time it gets called, you are effectively doing this:
var quest:int = questions.splice(8, 1)[0];
Since that index is beyond the end of the array, an empty array is returned and traces out as 0.

How to push an array in a for-loop statement, in ActionScript

I'm sorry if I'm being vague in any way as I'm nooby at AS3.0 and stackoverflow.
I simply wanna push the i variable to add to the variable _bullets.
var i:int = 0; //initializing the i variable
_bullets.push(i);
//Loops thought all the bullets on stage
for (var i:int = 0; i > _bullets.length; i++)
{
//Some code...
}
The result i wanna achieve is that the for-loop now has something to loop through. If more information is needed I will do my best to provide it.
I don't really understand what your are trying to do, but there are at least two mistakes in your code:
the variable i is declared two times: at the fist line, and in the loop.
the continuation test in the loop is wrong. It should be
for (var i:int = 0; i < _bullets.length; i++)
_bullets is supposed to be an Array of int ? So _bullets.push(i) will add the content of the variable i (here 0) at the end of your array. Is it what you wanted to do ?
Then, if you want to iterate through the elements of _bullets, you can use a for each loop if you don't care about the value of i:
for each (var bullet:int in _bullets )
{
// some code using bullet
}
it is equivalent to
for (var i:int = 0; i < _bullets.length; i++ )
{
var bullet:int = _bullet[i];
// some code using bullet
}

Why my function doesn't get my int var?! AS3

I have a trouble. I got my dear var myVar:int and an arr:Array. I want to use them to execute my function.
s1 and indice1 are array and integer values as I was defined in my program.
getIndex(s1, indice1);
function getIndex(arr:Array, index:int = 0):void {
for (var n:int = 0; n <= arr.length; n++) {
if (String(arr[n]).indexOf(">") >= 0) {
index = n;
trace(n);
arr[n] = String(arr[n]).substring(1);
}
}
}
now i get rigth results for my Array but i have a 0 for my index var.
Can someone help me?
I mean i need a dynamic way to assing index values of differents arrays to diferents indices so I can use my function to retrieve and index and save it for any Array I have
Your question is pretty unclear.
However, to answer (what I THINK you are asking),
You can not access variable index outside of the function. This is because the type int is not saved as a reference in AS3. To get index outside, you will have to do either of the following:
a) Assign the value of index to a global variable e.g.:
var gIndex:int;
function getIndex(arr:Array,index:int = 0):void{
//function contents
gIndex=index;
}
//This way you can access index as gIndex;
b) Return the variable index from the function
function getIndex(arr:Array,index:int = 0):int{
//function contents
return index;
}
//this way you can access index as getIndex(s1, indice1);
Your search string is available in arr[0] So that it returns 0.
Ok, I solve it.
Well it isn't what I want to but look.
I decided to return n value from my function and assing it to my var.
indice1 = getIndex(s1);
function getIndex(arr:Array){
for(var n:int=0; n<= arr.length; n++){
if( String(arr[n]).indexOf(">") >= 0){
return n;
arr[n]= String(arr[n]).substring(1);
}
}
}
So I got n value on my var and that's it. thanks Anyway =D

Resources