2015-01-21 79 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