You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Combinatorics/README.markdown
+16-16
Original file line number
Diff line number
Diff line change
@@ -366,26 +366,26 @@ The following code calculates Pascal's triangle in order to find the `C(n, k)` y
366
366
367
367
```swift
368
368
funcbinomialCoefficient(n: Int, _k: Int) ->Int {
369
-
var bc =Array2D(columns: n +1, rows: n +1, initialValue: 0)
370
-
371
-
for i in0...n {
372
-
bc[i, 0] =1
373
-
bc[i, i] =1
374
-
}
375
-
376
-
if n >0 {
377
-
for i in1...n {
378
-
for j in1..<i {
379
-
bc[i, j] = bc[i -1, j -1] + bc[i -1, j]
380
-
}
369
+
var bc =Array(count: n +1, repeatedValue: Array(count: n +1, repeatedValue: 0))
370
+
371
+
for i in0...n {
372
+
bc[i][0] =1
373
+
bc[i][i] =1
381
374
}
382
-
}
383
-
384
-
return bc[n, k]
375
+
376
+
if n >0 {
377
+
for i in1...n {
378
+
for j in1..<i {
379
+
bc[i][j] = bc[i -1][j -1] + bc[i -1][j]
380
+
}
381
+
}
382
+
}
383
+
384
+
return bc[n][k]
385
385
}
386
386
```
387
387
388
-
This uses [Array2D](../Array2D/) as helper code because Swift doesn't have a built-in two-dimensional array. The algorithm itself is quite simple: the first loop fills in the 1s at the outer edges of the triangle. The other loops calculate each number in the triangle by adding up the two numbers from the previous row.
388
+
The algorithm itself is quite simple: the first loop fills in the 1s at the outer edges of the triangle. The other loops calculate each number in the triangle by adding up the two numbers from the previous row.
389
389
390
390
Now you can calculate `C(66, 33)` without any problems:
0 commit comments