Go - Acronym

This commit is contained in:
2016-11-26 21:58:00 -06:00
parent 1abb8f7e73
commit 8ff43f2212
6 changed files with 180 additions and 1 deletions

27
go/acronym/README.md Normal file
View File

@@ -0,0 +1,27 @@
# Acronym
Convert a long phrase to its acronym
Techies love their TLA (Three Letter Acronyms)!
Help generate some jargon by writing a program that converts a long name
like Portable Network Graphics to its acronym (PNG).
To run the tests simply run the command `go test` in the exercise directory.
If the test suite contains benchmarks, you can run these with the `-bench`
flag:
go test -bench .
For more detailed info about the Go track see the [help
page](http://exercism.io/languages/go).
## Source
Julien Vanier [https://github.com/monkbroc](https://github.com/monkbroc)
## Submitting Incomplete Problems
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

46
go/acronym/acronym.go Normal file
View File

@@ -0,0 +1,46 @@
package acronym
import "strings"
const testVersion = 1
func abbreviate(inp string) string {
var ret string
for _, wrd := range strings.Fields(inp) {
var newWrd []rune
for _, b := range wrd {
if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') {
newWrd = append(newWrd, b)
} else {
if len(newWrd) > 0 {
ret = ret + testWord(string(newWrd))
newWrd = []rune{}
}
}
}
ret = ret + testWord(string(newWrd))
}
return strings.ToUpper(ret)
}
// testWord figures out the abbreviation letters for
// the given word
func testWord(inp string) string {
if len(inp) == 0 {
return ""
}
if inp == strings.ToUpper(inp) {
// the whole word is capitalized, return
// the first letter
return string(inp[0])
}
var ret string
// Find uppercase characters to return
for i, s := range inp {
st := string(s)
if i == 0 || st == strings.ToUpper(st) {
ret = ret + st
}
}
return ret
}

View File

@@ -0,0 +1,36 @@
package acronym
import (
"testing"
)
const targetTestVersion = 1
type testCase struct {
input string
expected string
}
var stringTestCases = []testCase{
{"Portable Network Graphics", "PNG"},
{"HyperText Markup Language", "HTML"},
{"Ruby on Rails", "ROR"},
{"PHP: Hypertext Preprocessor", "PHP"},
{"First In, First Out", "FIFO"},
{"Complementary metal-oxide semiconductor", "CMOS"},
}
func TestTestVersion(t *testing.T) {
if testVersion != targetTestVersion {
t.Errorf("Found testVersion = %v, want %v.", testVersion, targetTestVersion)
}
}
func TestAcronym(t *testing.T) {
for _, test := range stringTestCases {
actual := abbreviate(test.input)
if actual != test.expected {
t.Errorf("Acronym test [%s], expected [%s], actual [%s]", test.input, test.expected, actual)
}
}
}