Skip to content

Commit

Permalink
Merge pull request #602 from vaskoz/day295
Browse files Browse the repository at this point in the history
Day295
  • Loading branch information
vaskoz committed Jun 13, 2019
2 parents 6a10528 + abaa606 commit 709efe0
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
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)
}
}
}

0 comments on commit 709efe0

Please sign in to comment.