2015-01-21 74 views
0

我正在嘗試構建一個3D數組。這裏是我從2D數組修改的代碼。 3D陣列不會將我的陣列從我定義的值中打印出來。我的下標中有我的getter和setter錯誤。有人可以提醒我嗎?xcode swift 3D arrays

import UIKit 


class Array3D { 
    var zs:Int, ys:Int, xs:Int 
    var matrix: [Int] 


    init(zs: Int, ys:Int, xs:Int) { 
     self.zs = zs 
     self.ys = ys 
     self.xs = xs 
     matrix = Array(count:zs*ys*xs, repeatedValue:0) 
    } 

    subscript(z:Int, ys:Int, xs:Int) -> Int { 
     get { 
      return matrix[ zs * ys * xs + ys ] 
     } 
     set { 
      matrix[ zs* ys * xs + ys ] = newValue 
     } 
    } 

    func zsCount() -> Int { 
     return self.zs 
    } 

    func colCount() -> Int { 
     return self.ys 
    } 

    func rowCount() -> Int { 
     return self.xs 
    } 
} 

var dungeon = Array3D(zs: 5, ys: 5, xs: 5) 


dungeon[1,0,0] = 1 
dungeon[0,4,0] = 2 
dungeon[0,0,4] = 3 
dungeon[0,4,4] = 4 

print("You created a dungeon with \(dungeon.zsCount()) z value \(dungeon.colCount()) columns and \(dungeon.rowCount()) rows. Here is the dungeon visually:\n\n") 


for z in 0..<5 { 
for y in 0..<5 { 
    for x in 0..<5 { 
     print(String(dungeon[z,x,y])) 
    } 
    print("\n") 
} 
    print("\n") 
} 

回答

2

索引在下標中的計算方式存在錯誤。爲了(z, y, x)轉換爲線性座標,你可以使用:

z * ys * xs + y * xs + x 

所以標應該是固定的,如下所示:

subscript(z:Int, y:Int, x:Int) -> Int { 
    get { 
     return matrix[ z * ys * xs + y * xs + x ] 
    } 
    set { 
     matrix[ z * ys * xs + y * xs + x ] = newValue 
    } 
} 

注意,在循環內的打印語句索引倒:

print(String(dungeon[z,x,y])) 

它應該是[z, y, x]而不是

隨着這些改變,這是輸出I在操場獲得:

00003 
00000 
00000 
00000 
20004 

10000 
00000 
00000 
00000 
00000 

00000 
00000 
00000 
00000 
00000 

00000 
00000 
00000 
00000 
00000 

00000 
00000 
00000 
00000 
00000 

補遺 zsysxs代表3D矩陣的大小:有xs列,ys行和zs平面。每列的大小爲xs,每架飛機的尺寸爲xs * ys

對於y = 0和z = 0,與x = 3對應的數組中的元素是第4個元素,其索引爲3(數組基於零,以及三維座標)。如果y = 1,所述元件爲3 +的行的大小,其是3 + 5 = 8。爲了使它更通用

x + xs * y = 3 + 1 * 5 = 8 

代替每個平面的大小XS YS *,對應於25所以z座標必須乘以該大小。這導致用式I:

z * ys * xs + y * xs + x 

在z = 0的情況下,座標爲(0,1,3):

0 + 1 * 5 + 3 = 8 

如果Z = 1,則座標爲(1, 1,3),公式結果爲:

1 * 5 * 5 + 1 * 5 + 3 = 33 

等等。

如果這聽起來很複雜,請查看代碼生成的輸出,其中包含5個5行的塊,每個塊包含5個數字。如果將它翻譯爲單行(通過刪除換行符),可以通過從零計數到所需元素(從左到右)來獲取數組索引。您可以通過將5添加到索引並跳轉到下一行,並將其添加到下一個平面。

希望澄清一點。

+0

@Antonion謝謝!有用! z和zs,y和ys,x和xs有什麼區別?你會向我解釋爲什麼是線性座標z * ys * xs + y * xs + x?我真的很感謝你的幫助! – 2015-01-21 09:14:21

+0

@Cherry_thia更新了答案 - 希望它有幫助 – Antonio 2015-01-21 10:07:32

+0

感謝您的詳細解釋。我仍然需要一些時間來了解它,我很欣賞它。 – 2015-01-21 12:54:34