Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day295 #602

Merged
merged 2 commits into from
Jun 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,3 +301,4 @@ problems from
* [Day 288](https://github.com/vaskoz/dailycodingproblem-go/issues/590)
* [Day 290](https://github.com/vaskoz/dailycodingproblem-go/issues/594)
* [Day 291](https://github.com/vaskoz/dailycodingproblem-go/issues/596)
* [Day 295](https://github.com/vaskoz/dailycodingproblem-go/issues/601)
23 changes: 23 additions & 0 deletions day295/problem.go
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
}
38 changes: 38 additions & 0 deletions day295/problem_test.go
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)
}
}
}