Skip to content

Commit

Permalink
Merge pull request #16 from vaskoz/day7
Browse files Browse the repository at this point in the history
Day7
  • Loading branch information
vaskoz authored Aug 30, 2018
2 parents 1fcb2ad + 457d7b4 commit be928f4
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ problems from
* [Day 4](https://github.com/vaskoz/dailycodingproblem-go/issues/5)
* [Day 5](https://github.com/vaskoz/dailycodingproblem-go/issues/9)
* [Day 5 merge k sorted lists](https://github.com/vaskoz/dailycodingproblem-go/issues/11)

* [Day 6](https://github.com/vaskoz/dailycodingproblem-go/issues/13)
* [Day 7](https://github.com/vaskoz/dailycodingproblem-go/issues/15)
17 changes: 17 additions & 0 deletions day7/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package day7

// NumberOfDecodings calculates the number of possible decodings where
// letters are encoding as a=1, b=2 ... z=26
func NumberOfDecodings(str string) int {
if length := len(str); length == 0 || length == 1 {
return 1
}
var count int
if last := str[len(str)-1]; last > '0' && last <= '9' {
count = NumberOfDecodings(str[:len(str)-1])
}
if second := str[len(str)-2]; second == '1' || second == '2' && str[len(str)-1] < '7' {
count += NumberOfDecodings(str[:len(str)-2])
}
return count
}
29 changes: 29 additions & 0 deletions day7/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day7

import "testing"

var testcases = []struct {
input string
expected int
}{
{"111", 3},
{"1111", 5},
{"2626", 4},
{"1234", 3},
}

func TestNumberOfDecodings(t *testing.T) {
for _, tc := range testcases {
if result := NumberOfDecodings(tc.input); result != tc.expected {
t.Errorf("For input %v, expected %v but got %v", tc.input, tc.expected, result)
}
}
}

func BenchmarkNumberOfDecodings(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
NumberOfDecodings(tc.input)
}
}
}

0 comments on commit be928f4

Please sign in to comment.