Skip to content

Commit 5205fc8

Browse files
author
Deep Parekh
committed
Added checks for subscript and fixed initializer compile error
1 parent 8da897d commit 5205fc8

File tree

1 file changed

+40
-29
lines changed

1 file changed

+40
-29
lines changed
Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,42 @@
11
/*
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+
*/
66
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)
2015
}
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
2336
}
24-
}
2537
}
2638

2739

28-
2940
// initialization
3041
var matrix = Array2D(columns: 3, rows: 5, initialValue: 0)
3142

@@ -51,13 +62,13 @@ print(matrix.array)
5162

5263
// print out the 2D array with a reference around the grid
5364
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+
}
6072
}
61-
}
62-
print("]")
73+
print("]")
6374
}

0 commit comments

Comments
 (0)