2016-05-05 75 views
0

此刻我試圖將16乘4的數組轉換爲16乘2的數組。我通過總結4行然後將行值賦值爲關鍵字(因此在此之後fitness [0,0]可以是[x,0]而fitness [1,0]將是[y,1])我想使用sortOn方法排序第一列(我的例子中的x和y)的健身數組。由於某種原因,這是行不通的。有沒有關於我的代碼有什麼問題的建議?在actionscript中對多維數組進行排序

var i = int; 
var j = int; 
var temp = int; 
var sum = int; 
sum = 0; 
for (i = 0; i <16; i++) { 
    for (j = 0; j < 4; j++) { 
     temp = genotype[i][j]; 
     sum = sum + temp; 
    } 
    fitness[i] = [sum,i]; 
    sum = 0; 
} 

fitness.sortOn("0"); 

回答

0

你應該認爲sortOn()排序的元素中的陣列按照陣列中的屬性注意。該陣列應該具有以下特徵:

  1. 該數組是一個索引數組,而不是關聯數組。
  2. 該陣列的每個元素都包含具有一個或多個屬性的object
  3. 所有對象至少有共同的一個屬性,其值可用於排序數組。

那麼,這是一個數組:

var a:Array = ["a", "b", "c"]

這是一個對象(又名關聯陣列):

var o:Object = {"name":"Tom", "age":21, "single":true}

這是結構的類型sortOn()方法適用於:

var a:Array = [ 
    {"name":"Tom", "age":21, "single":true}, 
    {"name":"Dick", "age":36, "single":false}, 
    {"name":"Harry", "age":27, "single":true} 
] 

此外,當您聲明一個變量的模式是NAME:TYPE = VALUE,而不是NAME = TYPE

下面是相應的代碼。你已經添加了print()函數,它追蹤出數組的內容,以便你可以看到前後的數據。

/* --- Code that wasn't provided --- */ 
// This creates the data so we can test sorting it. 

var genotype:Array = []; 
for (var r:int = 0; r < 16; r++) { 
    var row:Array = []; 
    for (var c:int = 0; c < 4; c++) { 
     row.push(Math.floor(Math.random() * 100)); 
    } 
    genotype.push(row) 
} 

var fitness:Array = []; 

/* --- Modified Original Code --- */ 
// Loop through the genotype, and create entries in fitness with the sum and index 
for (var i:int = 0; i < genotype.length; i++) { 
    fitness[i] = {"sum":sumArray(genotype[i]), "index":i}; 
} 

function sumArray(a:Array):Number { 
    // This simply adds up the total values in an array. 
    var sum:int = 0; 
    for (var i:int = 0; i < a.length; i++) { 
     sum += a[i]; 
    } 
    return sum; 
} 

fitness.sortOn("sum", Array.NUMERIC); // Sort on the sum property, numerically ascending. 


// To sort the original data, I'm going to place it into a new array. 
var newGeno:Array = []; 
i = 0; 
for each (var entry:Object in fitness) { 
    newGeno[i] = genotype[entry.index]; 
    i++; 
} 

/* If you want, you can replace the original, simply add... 
    genotype = newGeno; 
*/ 

trace("--- GENOTYPE ---") 
print(genotype); 

trace("--- NEW GENO ---") 
print(newGeno); 

function print(a:Array, prefix:String = ""):void { 
    for (var i:int = 0; i < a.length; i++) { 
     if (a[i] is Array) { 
      trace(prefix + i + ": [Array] " + sumArray(a[i])); 
      print(a[i], prefix + " "); 
     } else { 
      trace(prefix + i + ": " + a[i]) 
     } 
    } 
} 
相關問題