22: names scores

This commit is contained in:
VicRen
2020-10-21 08:54:53 +08:00
parent 64d25a8714
commit d90cbe600d
8 changed files with 113 additions and 0 deletions

48
22_names_scores/main.go Normal file
View 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
}

File diff suppressed because one or more lines are too long

View 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)
}
})
}
}