Skip to content

Commit 52b8557

Browse files
committed
Merge pull request #69 from Thecmar7/master
Add playground for Array2D
2 parents ecd1ee3 + c316fa9 commit 52b8557

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
*/
6+
public struct Array2D<T> {
7+
public let columns: Int
8+
public let rows: Int
9+
private var array: [T]
10+
11+
public init(columns: Int, rows: Int, initialValue: T) {
12+
self.columns = columns
13+
self.rows = rows
14+
array = .init(count: rows*columns, repeatedValue: initialValue)
15+
}
16+
17+
public subscript(column: Int, row: Int) -> T {
18+
get {
19+
return array[row*columns + column]
20+
}
21+
set {
22+
array[row*columns + column] = newValue
23+
}
24+
}
25+
26+
}
27+
28+
// initialization
29+
var Array2DNumbers = Array2D(columns: 3, rows: 5, initialValue: 0)
30+
31+
// makes an array of rows * columns elements all filled with zero
32+
print(Array2DNumbers.array)
33+
34+
// setting numbers using subscript [x, y]
35+
Array2DNumbers[0, 0] = 1
36+
Array2DNumbers[1, 0] = 2
37+
38+
Array2DNumbers[0, 1] = 3
39+
Array2DNumbers[1, 1] = 4
40+
41+
Array2DNumbers[0, 2] = 5
42+
Array2DNumbers[1, 2] = 6
43+
44+
Array2DNumbers[0, 3] = 7
45+
Array2DNumbers[1, 3] = 8
46+
Array2DNumbers[2, 3] = 9
47+
48+
// now the numbers are set in the array
49+
print(Array2DNumbers.array)
50+
51+
// print out the 2D array with a reference around the grid
52+
for i in 0..<Array2DNumbers.rows {
53+
print("[", terminator: "");
54+
for j in 0..<Array2DNumbers.columns {
55+
if (j == Array2DNumbers.columns - 1) {
56+
print("\(Array2DNumbers[j, i])", terminator: "");
57+
} else {
58+
print("\(Array2DNumbers[j, i]) ", terminator: "");
59+
}
60+
}
61+
print("]");
62+
}
63+
64+
65+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>

0 commit comments

Comments
 (0)