go 分金币, switch case和字符用法
package main
import (
"fmt"
)
var (
coins = 100
users = []string {
"Matthew", "sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth",
}
distribution = make(map[string]int,len(users))
)
func calcCoin(username string) int {
var sum int = 0
for _, char := range username{
switch char {
case 'a','A':
sum = sum+1
case 'e','E':
sum = sum+1
case 'i','I':
sum = sum+2
case 'o','O':
sum = sum+3
case 'u','U':
sum = sum+5
}
}
return sum
}
func dispatchCoin()int {
var left int = coins
for _,username := range users{
allCoin := calcCoin(username)
left = left - allCoin
value,ok := distribution[username]
if !ok{
distribution[username] = allCoin
}else{
distribution[username] = value + allCoin
}
}
return left
}
func main() {
left := dispatchCoin()
for username,coin:=range distribution{
fmt.Printf("user:%s have %d coins\n",username,coin)
}
fmt.Printf("left coin:%d \n",left)
}
输出:
user:Elizabeth have 5 coins
user:Augustus have 16 coins
user:Heidi have 5 coins
user:Emilie have 6 coins
user:Aaron have 5 coins
user:Adriano have 7 coins
user:Matthew have 2 coins
user:sarah have 2 coins
user:Peter have 2 coins
user:Giana have 4 coins
left coin:46
写入自己的博客中才能记得长久