-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #602 from vaskoz/day295
Day295
- Loading branch information
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package day295 | ||
|
||
// PascalTriangleRow returns a particular row in Pascal's triangle. | ||
// Runs in O(row) time and space. | ||
func PascalTriangleRow(row int) []int { | ||
result := make([]int, row+1) | ||
for entry := range result { | ||
result[entry] = combinations(row, entry) | ||
} | ||
return result | ||
} | ||
|
||
func combinations(n, k int) int { | ||
return factorial(n) / (factorial(k) * factorial(n-k)) | ||
} | ||
|
||
func factorial(n int) int { | ||
result := 1 | ||
for i := 2; i <= n; i++ { | ||
result *= i | ||
} | ||
return result | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package day295 | ||
|
||
import ( | ||
"reflect" | ||
"testing" | ||
) | ||
|
||
// nolint | ||
var testcases = []struct { | ||
row int | ||
expected []int | ||
}{ | ||
{0, []int{1}}, | ||
{1, []int{1, 1}}, | ||
{2, []int{1, 2, 1}}, | ||
{3, []int{1, 3, 3, 1}}, | ||
{4, []int{1, 4, 6, 4, 1}}, | ||
{5, []int{1, 5, 10, 10, 5, 1}}, | ||
{6, []int{1, 6, 15, 20, 15, 6, 1}}, | ||
{7, []int{1, 7, 21, 35, 35, 21, 7, 1}}, | ||
} | ||
|
||
func TestPascalTriangleRow(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result := PascalTriangleRow(tc.row); !reflect.DeepEqual(result, tc.expected) { | ||
t.Errorf("Expected %v, got %v", tc.expected, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkPascalTriangleRow(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
PascalTriangleRow(tc.row) | ||
} | ||
} | ||
} |