mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 20:04:43 +01:00
22: names scores
This commit is contained in:
48
22_names_scores/main.go
Normal file
48
22_names_scores/main.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const BASE = 64
|
||||
|
||||
func main() {
|
||||
b, err := ioutil.ReadFile("names.txt")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
names := readNames(string(b))
|
||||
sort.Strings(names)
|
||||
fmt.Println(names)
|
||||
sum := 0
|
||||
for n, name := range names {
|
||||
sum += (n + 1) * worthOf(name)
|
||||
}
|
||||
fmt.Println("sum:", sum)
|
||||
}
|
||||
|
||||
func readNames(s string) []string {
|
||||
if len(s) == 0 {
|
||||
return nil
|
||||
}
|
||||
str := strings.Replace(s, "\"", "", -1)
|
||||
ret := strings.Split(str, ",")
|
||||
return ret
|
||||
}
|
||||
|
||||
func worthOf(word string) int {
|
||||
if len(word) == 0 {
|
||||
return 0
|
||||
}
|
||||
sum := 0
|
||||
for i := 0; i < len(word); i++ {
|
||||
a := word[i : i+1][0]
|
||||
w := uint8(a) - BASE
|
||||
sum += int(w)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
1
22_names_scores/names.txt
Normal file
1
22_names_scores/names.txt
Normal file
File diff suppressed because one or more lines are too long
64
22_names_scores/names_scores_test.go
Normal file
64
22_names_scores/names_scores_test.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_readNames(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
input string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
"empty_input",
|
||||
"",
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"one_name",
|
||||
"\"VIC\"",
|
||||
[]string{"VIC"},
|
||||
},
|
||||
{
|
||||
"two_names",
|
||||
"\"VIC\",\"COCO\"",
|
||||
[]string{"VIC", "COCO"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := readNames(tc.input)
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("readNames() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_worthOf(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
word string
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"COLIN",
|
||||
"COLIN",
|
||||
53,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fmt.Printf("%d", 'A')
|
||||
got := worthOf(tc.word)
|
||||
if got != tc.want {
|
||||
t.Errorf("worthOf() = %d, want %d", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user