How would one go about finding the greatest number in an array of numbers? For example, if you had an array like this:
(4, 8, 3, 19, 6, 11)
What would be the code used to rifle through the entire array until the greatest number in the array, in this case 19, was found and then return it’s index position?
ActionScript Code:
[LEFT][COLOR=#000000]function[/COLOR] biggestNumberCOLOR=#000000[/COLOR]:[COLOR=#0000FF]Number[/COLOR] [COLOR=#000000]{[/COLOR]
bigNum = [COLOR=#000080]0[/COLOR];
[COLOR=#0000FF]for[/COLOR][COLOR=#000000]([/COLOR][COLOR=#000000]var[/COLOR] i:[COLOR=#0000FF]Number[/COLOR] = [COLOR=#000080]0[/COLOR]; i > [COLOR=#0000FF]array[/COLOR].[COLOR=#0000FF]length[/COLOR]; i++[COLOR=#000000])[/COLOR] [COLOR=#000000]{[/COLOR]
[COLOR=#0000FF]if[/COLOR][COLOR=#000000]([/COLOR]bigNum < [COLOR=#0000FF]array[/COLOR][COLOR=#000000][[/COLOR]i[COLOR=#000000]][/COLOR][COLOR=#000000])[/COLOR] [COLOR=#000000]{[/COLOR]
bigNum = [COLOR=#000000][/COLOR]i[COLOR=#000000][/COLOR];
[COLOR=#000000]}[/COLOR]
[COLOR=#0000FF]return[/COLOR] bigNum;
[COLOR=#000000]}[/COLOR]
[/LEFT]
Nevermind, easy question I guess. I figured it out pretty quickly.
var myVar = my_array[0];
for (var i:int=0; i<my_array.length; i++){
if(my_array* >= myVar){
myVar = my_array*;
}
}
trace(myVar);
You could also do:
var arr:Array = [12, 1, 7, 15, 3];
trace(arr.sort(Array.NUMERIC).pop()); //15
[QUOTE=TheCanadian;2327926]You could also do:
var arr:Array = [12, 1, 7, 15, 3];
trace(arr.sort(Array.NUMERIC).pop()); //15
[/QUOTE]
Noice! I love efficient code. 
Noice! I love efficient code.
Ironically, though, sorting the array is probably going to take O(n log(n)), whereas finding the greatest element will take O(n). Of course, maybe Flash’s internal array sort is faster than using a loop in ActionScript, but I think that the conciseness is the coolest part of TheCanadian’s code.
You say “potato” i say “efficient”. I meant nice and neat rather than computationally faster! I should be more careful with my word choices 