forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray2D.swift
More file actions
28 lines (25 loc) · 875 Bytes
/
Array2D.swift
File metadata and controls
28 lines (25 loc) · 875 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
Two-dimensional array with a fixed number of rows and columns.
This is mostly handy for games that are played on a grid, such as chess.
Performance is always O(1).
*/
public struct Array2D<T> {
public let columns: Int
public let rows: Int
private var array: [T]
public init(columns: Int, rows: Int, initialValue: T) {
self.columns = columns
self.rows = rows
array = .init(count: rows*columns, repeatedValue: initialValue)
}
public subscript(column: Int, row: Int) -> T {
get {
return array[row*columns + column]
}
set {
precondition(row < rows, "Row \(row) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
precondition(column < columns, "Column \(column) Index is out of range. Array<T>(columns: \(columns), rows:\(rows))")
array[row*columns + column] = newValue
}
}
}