1
1
/*
2
- Two-dimensional array with a fixed number of rows and columns.
3
- This is mostly handy for games that are played on a grid, such as chess.
4
- Performance is always O(1).
5
- */
2
+ Two-dimensional array with a fixed number of rows and columns.
3
+ This is mostly handy for games that are played on a grid, such as chess.
4
+ Performance is always O(1).
5
+ */
6
6
public struct Array2D < T> {
7
- public let columns : Int
8
- public let rows : Int
9
- fileprivate var array : [ T ]
10
-
11
- public init ( columns: Int , rows: Int , initialValue: T ) {
12
- self . columns = columns
13
- self . rows = rows
14
- array = . init( repeatElement ( initialValue, count: rows*columns) )
15
- }
16
-
17
- public subscript( column: Int , row: Int ) -> T {
18
- get {
19
- return array [ row*columns + column]
7
+ public let columns : Int
8
+ public let rows : Int
9
+ public var array : [ T ]
10
+
11
+ public init ( columns: Int , rows: Int , initialValue: T ) {
12
+ self . columns = columns
13
+ self . rows = rows
14
+ array = [ T] ( repeating: initialValue, count: rows*columns)
20
15
}
21
- set {
22
- array [ row*columns + column] = newValue
16
+
17
+ public subscript( column: Int , row: Int ) -> T {
18
+ get {
19
+ if isValidSubscript ( column: column, row: row) {
20
+ return array [ row*columns + column]
21
+ } else {
22
+ fatalError ( " Not a valid subscript " )
23
+ }
24
+ }
25
+ set {
26
+ if isValidSubscript ( column: column, row: row) {
27
+ array [ row*columns + column] = newValue
28
+ } else {
29
+ fatalError ( " Not a valid subscript " )
30
+ }
31
+ }
32
+ }
33
+
34
+ private func isValidSubscript( column: Int , row: Int ) -> Bool {
35
+ return column < columns && row < rows
23
36
}
24
- }
25
37
}
26
38
27
39
28
-
29
40
// initialization
30
41
var matrix = Array2D ( columns: 3 , rows: 5 , initialValue: 0 )
31
42
@@ -51,13 +62,13 @@ print(matrix.array)
51
62
52
63
// print out the 2D array with a reference around the grid
53
64
for i in 0 ..< matrix. rows {
54
- print ( " [ " , terminator: " " )
55
- for j in 0 ..< matrix. columns {
56
- if j == matrix. columns - 1 {
57
- print ( " \( matrix [ j, i] ) " , terminator: " " )
58
- } else {
59
- print ( " \( matrix [ j, i] ) " , terminator: " " )
65
+ print ( " [ " , terminator: " " )
66
+ for j in 0 ..< matrix. columns {
67
+ if j == matrix. columns - 1 {
68
+ print ( " \( matrix [ j, i] ) " , terminator: " " )
69
+ } else {
70
+ print ( " \( matrix [ j, i] ) " , terminator: " " )
71
+ }
60
72
}
61
- }
62
- print ( " ] " )
73
+ print ( " ] " )
63
74
}
0 commit comments