-
Notifications
You must be signed in to change notification settings - Fork 31
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 #16 from vaskoz/day7
Day7
- Loading branch information
Showing
3 changed files
with
48 additions
and
1 deletion.
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,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 | ||
} |
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,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) | ||
} | ||
} | ||
} |