Greatest & smallest code outputs undefined but can't figure out why - undefined

I am fairly new to code and the below is outputting undefined, can anyone point me in the right direction as to why?
As the function alludes I'm just trying to find the biggest and smallest numbers in a sequence.
function findBiggestAndSmallest(numbers) {
var biggest = numbers[0] ;
var smallest = numbers[0];
for (var i= 0; i < numbers.length; i++){
var number = numbers[i];
if(biggest < number){
biggest = number;
}
}
for (var i= 0; i < numbers.length; i++){
var number = numbers[i];
if(smallest > number){
smallest = number;
}
}
console.log ( 'biggest: ' + biggest + ', ' + 'smallest: ' + smallest);
}

Related

How to merge arrays by index AS3

Seeking a way to merge arrays by index like so:
var a1:Array = ["a", "b", "c"];
var a2:Array = ["1", "2", "3"];
var a3:Array = result: ["a", 1, "b", 2, "c", 3]
I've tried concat, push, splice... not getting close. Thanks.
function arrayMerge(arr1:Array, arr2:Array):Array {
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
return o;
}
Thanks Payam for answer and non-judgement. Here's how I applied your work:
var arr1:Array = ["question1", "question2", "question3"];
var arr2:Array = ["answer1", "answer2", "answer3"];
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
trace(o); //(question1,answer1,question2,answer2,question3,question3)
#AndyH :
payamsbr is right, but you may work with Vectors or Arrays
Perhaps tl; dr; but this is the principle.
If You want to understand something try those possibilities.
If you don't, just copy and paste some shorter code ;)
var v1:Vector.<String> = new <String>["a", "b", "c"];
var v2:Vector.<uint> = new <uint>[1, 2, 3]; // why do you use String here and not uint?
// if you want to convert a uint to a String, use myUint.toString();
function convertVectorToArray(v1:Vector.<String>,v2:Vector.<uint>):Array{
var mergedArray:Array = new Array();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same lenfgth!"));
}else{
for(var i:uint = 0; i <v1.length ; i++){
mergedArray.push(v1[i]);
mergedArray.push(v2[i]);
}
}
return(mergedArray);
}
function mergeVectors(v1:Vector.<String>,v2:Vector.<uint>):Vector.<Object>{
var mergedVector:Vector.<Object> = new Vector.<Object>();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}
for(var i:uint = 0; i <v1.length ; i++){
mergedVector.push(v1[i] as String);
mergedVector.push(v2[i] as uint);
}
return(mergedVector);
}
var mergedArray:Array = (convertVectorToArray(v1,v2));
var mergedVector:Vector.<Object> = (mergeVectors(v1,v2));
function listArray(arr:Array):String{
var str: String="";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < arr.length ; i++){
str+="typeof(arr[" + i + "]) = " + (typeof(arr[i]) as String).toUpperCase() + ", value = " + arr[i] + "\n";
}
}
return str;
}
function listVector(vect:Vector.<Object>):String{
var str: String = "";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < vect.length ; i++){
str+="typeof(vect[" + i + "]) = " + (typeof(vect[i]) as String).toUpperCase() + ", value = " + vect[i] + "\n";
}
}
return str;
}
trace(listArray(mergedArray));
trace(listVector(mergedVector));
You may add a sort() method if You need it (you didn't told about it)
And Always throw an Error if the 2 Arrays or Vectors don't have the same length!
Throwing an Error is the best way to understand if something goes wrong...
This will avoid You a lot of time if You need to debug Your code!!!
As You can see the output is the same, but if the Vector Class is used correctly, this is more efficient than an Array.
Output :
Since there's a Vector Class, I don't understand a lot of people who chose Arrays instead...
Of course Vector. is a nonsense, but I posted it anyway so You can figure You out the Vector Class.
Output is the same :
typeof(arr[0]) = STRING, value = a
typeof(arr[1]) = NUMBER, value = 1
typeof(arr[2]) = STRING, value = b
typeof(arr[3]) = NUMBER, value = 2
typeof(arr[4]) = STRING, value = c
typeof(arr[5]) = NUMBER, value = 3
typeof(vect[0]) = STRING, value = a
typeof(vect[1]) = NUMBER, value = 1
typeof(vect[2]) = STRING, value = b
typeof(vect[3]) = NUMBER, value = 2
typeof(vect[4]) = STRING, value = c
typeof(vect[5]) = NUMBER, value = 3
I forgot this easiest way if you really want an Array...
Quick done!
var ar1:Array = [1,2,3];
var ar2:Array = ["a","b","c"];
function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
trace(merge(ar1, ar2));
// outputs : 1,2,3,a,b,c
Another possibility :
function populateObject(v1:Vector.<String>, v2:Vector.<uint>):Object{
var obj = new Object();
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < v1.length; i++){
obj[v2[i]] = v1[i];
}
}
return obj;
}
var o:Object = populateObject(v1,v2);
function listObject(someObj:Object):void{
var myObj:Object = someObj;
for (var i:String in someObj){
trace(someObj[i] + ": " + i);
}
}
listObject(o);
output =
a: 1
b: 2
c: 3
I think that You have a lot of possibilities to use here even it's my longer answer ;)
If You try those possibilities and understand them, this will certainty help You to think to find the best way to deal with Your issue.
But You may also copy and paste some shorter code.
I just wanted to show You that there's more than one answer.
If you understand this, You will be able to go further with coding.
Have fun ;)
Sincerely.
Nicolas
Best regards.
Nicolas.

adding X amount of addChild per maxvalue in loop

The assignment is the spawn several light and dark feathers according to score points from a quiz. The light feathers symbolize the correct points (light_feather), and the dark feather are the incorrect points (dark_feather) (Each are being tracked). All the feathers are supposed to line up on one line, meaning first light feathers, followed by the dark feathers. I got the quiz dynamics figured out, and the function I have posted here is only for when they press end quiz.
var light_feather:LightFeather = new LightFeather();
var dark_feather:DarkFeather = new DarkFeather();
var good_answers:uint = 0;
var bad_answers:uint = 0;
function avsluttFunc (evt:MouseEvent)
{
var sum_LightFeatherX:Number = 0;
for (var i = 0; i < good_answers; i++) {
addChild(light_feather);
light_feather.x += 12 + (i*16);
light_feather.y = 0;
trace("Lys X-verdi: " + light_feather.x);
sum_LightFeatherX += Number(light_feather.x);
return sum_LightFeatherX;
}
trace(sum_LightFeatherX);
dark_feather.x += sum_LightFeatherX;
for (var j = 1; j <= bad_answers; j++) {
addChild(dark_feather);
dark_feather.x += 12 + (j*16);
dark_feather.y = 0;
trace("Mørk X-verdi: " + dark_feather.x);
}
/*
//Resetter poengsummen
good_answers = 0;
bad_answers = 0;
*/
}
You can do what you are looking for using only one for loop, take a look :
var good_answers:uint = 2;
var bad_answers:uint = 4;
function avsluttFunc(evt:MouseEvent)
{
for (var i:int = 0; i < good_answers + bad_answers; i++) {
var feather:DisplayObject = i < good_answers ? new LightFeather() : new DarkFeather();
feather.x += 12 + i * (feather.width + 1);
feather.y = 0;
addChild(feather);
}
}
This code example will create 4 DarkFeather instances next to 2 LightFeather ones.
Edit :
How to add your objects to an array ?
// feathers array should be accessible for both codes (adding and removing objects)
var feathers:Array = [];
for (var i:int = 0; i < good_answers + bad_answers; i++) {
var feather:DisplayObject = i < good_answers ? new LightFeather() : new DarkFeather();
addChild(feather);
feathers.push(feather);
}
then to remove them from the stage, you can do for example :
for (var i:int = 0; i < feathers.length; i++) {
var feather:DisplayObject = DisplayObject(feathers[i]);
feather.parent.removeChild(feather);
}
Hope that can help.

Checking for straight combination in poker

I want to check for a straight combination in a poker game.
So, I have this array: var tempArr:Array = new Array;
I have this for sorting the array:
for (i = 0; i < 7; i++)
{
tempArr[i] = pValue[i];
}
tempArr.sort( Array.NUMERIC );
pValue is the value of the cards, it's have range from 2 to 14.
So, if I have this Array: tempArray = [2,3,3,4,5,5,6];
How can I check if I have a straight combination in my hand?
Set a bucket array to save if you got a card in hand
var t:Array = [];
//t[2] = 1;mean you have 2
// t[3] = 0;mean you don't have 3
//first initialize t
for(var i:int = 0; i < 15; i++)
{
t[i] = 0;
}
//then set the values from tempArray
for (var j:int = 0; j < tempArray.length; j++)
{
t[tempArray[j]] = 1;
}
//if you have a straight combination in your hand
//you will get a k that t[k] & t[k-1]& t[k-2] & t[k-3] & t[k-4] == 1
var existed:boolean = false;//the flag save if you got a straight combination
for (var k:int = t.length - 1; k >= 4; k--)
{
if (t[k] == 0)
{
continue;
}
if ((t[k] & t[k-1] & t[k-2] & t[k-3] & t[k-4]) == 1)
{
existed = true;
break;
}
}

Creating Multiple Values In For Loop [AS3]

I am trying to create multiple Numbers with for loop.
var sasutu1x : Number = Number(sasutu1.text);
var sasutu2x : Number = Number(sasutu2.text);
var sasutu3x : Number = Number(sasutu3.text);
var sasutu4x : Number = Number(sasutu4.text);
var sasutu5x : Number = Number(sasutu5.text);
var sasutu6x : Number = Number(sasutu6.text);
My Solution :
var i:int;
for (i = 0; i < 7; i++)
{
var this["sasutu" i + "x"] : Number = Number(["sasutu" + i].text);
}
Thanks for you help.
You can use a Vector, or if you want to get a reference to that number by name later, you can also use a Dictionary.
var i:int;
var sasutuDict:Dictionary = new Dictionary(true);
for (i = 0; i < 7; i++)
{
sasutuDict["sasutu" i + "x"] = Number(["sasutu" + i].text);
}
One advantage of a dictionary, is that you can even do something like this:
for (i = 0; i < 7; i++)
{
var sasutuTexField:TextField = this["sasutu" + i];
sasutuDict[sasutuTexField] = Number(sasutuTexField.text);
}
Meaning you can have the key of the dictionary be the text field itself.
A better solution would be to use a Vector instead.
var vec:Vector.<int> = new Vector.<int>();
for (var i:int = 0; i < 7; i++)
{
vec.push(Number(["sasutu"+i].text));
}

Percentage Distribution of numbers in AS3

I need to generate 238 numbers, with a range of 1-4, but I want to weight them, so there's say 35% chance of getting 3, 28% chance of getting 2, 18% chance of getting 4m, and 19% chance of getting 1.
I found this..
def select( values ):
variate = random.random() * sum( values.values() )
cumulative = 0.0
for item, weight in values.items():
cumulative += weight
if variate < cumulative: return item
return item # Shouldn't get here, but just in case of rounding... print select( { "a": 70, "b": 20, "c": 10 } )
But I don't see how to convert that to AS3?
I would do something like this:
var values:Array = [1,2,3,4];
var weights:Array = [35, 28, 18, 19];
var total:Number = 0;
for(var i in weights) {
total += weights[i];
}
var rndNum:Number = Math.floor(Math.random()*total);
var counter:Number = 0;
for(var j:Number = 0; j<weights.length; j++) {
counter += weights[j];
if( rndNum <= counter ) return values[j]; //This is the value
}
(untested code, but the idea should work)
Take a look at this article:
http://uihacker.blogspot.com/2009/09/actionscript-3-choose-random-item-from.html
You can also use Rnd.bit() to get a weighted 1 or 0 and adapt it to your situation.
Here for you:
/**
* random due to weighted values
*
* #param {{}} spec such as {'a':0.999, 'b':0.001}
* #return {*} return the key in object
*/
public static function weightedRand(spec:Object):* {
var i:String, j:int, table:Array = [];
for (i in spec) {
// from: https://stackoverflow.com/questions/8435183/generate-a-weighted-random-number
// The constant 10 below should be computed based on the
// weights in the spec for a correct and optimal table size.
// E.g. the spec {0:0.999, 1:0.001} will break this impl.
for (j=0; j<spec[i]*10; j++) {
table.push(i);
}
}
return table[Math.floor(Math.random() * table.length)];
}
Then you could test with this code:
public static function main():void {
// test calculate weighted rand
// random weighted
var result:Array = [];
for (var k:int = 0; k < 100; k++) {
var rand012:String = MyUtil.weightedRand({'y': 0.8, 'n1': 0.1, 'n2': 0.1});
result.push(rand012); // random in distribution...
}
logger.traceObject('result: ', result);
// counts
var counts:Object = {};
var totalCounts:int = 0;
for (var i:int = 0; i < result.length; i++) {
counts[result[i]] = 1 + (counts[result[i]] || 0);
totalCounts++;
}
logger.traceObject('counts: ', counts);
// ratios
var ratios:Object = {};
for (var c:String in counts) {
ratios[c] = counts[c] / totalCounts;
}
logger.traceObject('ratios: ', ratios);
}