Skip to content

Instantly share code, notes, and snippets.

@benjic
Created April 4, 2015 23:56
Show Gist options
  • Save benjic/820f5c0c9e86db71bd37 to your computer and use it in GitHub Desktop.
Save benjic/820f5c0c9e86db71bd37 to your computer and use it in GitHub Desktop.
PASS
BenchmarkConvertA 300000 5625 ns/op
BenchmarkConvertB 300000 5756 ns/op
ok _/home/benjica/exercism/go/raindrops 3.532s
package raindrops
import "fmt"
func Convert(num int) string {
return ConvertCompare(num, "A")
}
func ConvertCompare(num int, compare string) string {
// We build a map of the language
// We have to preserve order so slices are required
words := []string{"Pling", "Plang", "Plong"}
factors := []int{3, 5, 7}
if compare == "A" {
return ConvertFactorMapA(num, words, factors)
} else {
return ConvertFactorMapB(num, words, factors)
}
}
func ConvertFactorMapA(num int, words []string, factors []int) string {
var speak string
// Determine if given num is composed of any of the factors
for i, factor := range factors {
if num%factor == 0 {
speak += fmt.Sprintf(words[i])
}
}
// If string was not modified by map, emit num
if len(speak) == 0 {
speak += fmt.Sprintf("%d", num)
}
return speak
}
func ConvertFactorMapB(num int, words []string, factors []int) string {
var speak string
// Determine if given num is composed of any of the factors
for i, factor := range factors {
if num%factor == 0 {
speak += fmt.Sprintf(words[i])
}
}
// If string was not modified by map, emit num
if speak == "" {
speak += fmt.Sprintf("%d", num)
}
return speak
}
package raindrops
import "testing"
var tests = []struct {
input int
expected string
}{
{1, "1"},
{3, "Pling"},
{5, "Plang"},
{7, "Plong"},
{6, "Pling"},
{9, "Pling"},
{10, "Plang"},
{14, "Plong"},
{15, "PlingPlang"},
{21, "PlingPlong"},
{25, "Plang"},
{35, "PlangPlong"},
{49, "Plong"},
{52, "52"},
{105, "PlingPlangPlong"},
{12121, "12121"},
}
func TestConvert(t *testing.T) {
for _, test := range tests {
if actual := Convert(test.input); actual != test.expected {
t.Errorf("Convert(%d) = %q, expected %q.",
test.input, actual, test.expected)
}
}
}
func BenchmarkConvertA(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range tests {
ConvertCompare(test.input, "A")
}
}
}
func BenchmarkConvertB(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range tests {
ConvertCompare(test.input, "B")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment