|
4 | 4 | Performance is always O(1).
|
5 | 5 | */
|
6 | 6 | public struct Array2D<T> {
|
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) |
| 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 = [T](repeating: initialValue, count: rows*columns) |
| 15 | + } |
| 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 | + } |
15 | 24 | }
|
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 |
| 25 | + set { |
| 26 | + if isValidSubscript(column: column, row: row) { |
| 27 | + array[row*columns + column] = newValue |
| 28 | + } else { |
| 29 | + fatalError("Not a valid subscript") |
| 30 | + } |
36 | 31 | }
|
| 32 | + } |
| 33 | + |
| 34 | + private func isValidSubscript(column: Int, row: Int) -> Bool { |
| 35 | + return column < columns && row < rows |
| 36 | + } |
37 | 37 | }
|
38 | 38 |
|
39 | 39 |
|
@@ -62,13 +62,13 @@ print(matrix.array)
|
62 | 62 |
|
63 | 63 | // print out the 2D array with a reference around the grid
|
64 | 64 | for i in 0..<matrix.rows {
|
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 |
| - } |
| 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: "") |
72 | 71 | }
|
73 |
| - print("]") |
| 72 | + } |
| 73 | + print("]") |
74 | 74 | }
|
0 commit comments