1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package main
import "fmt"
var ( coins = 50 users = []string{ "Matthew", "Sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth", } distribution = make(map[string]int, len(users)) )
func dispatchCoin() (left int) { /* 思路: 1.依次拿到每个人的名字,遍历users 2.获取到一个名字根据规则分配金币 2.1.没人分得金币数应该保存到distribution中 2.2.计算剩余金币数量 */ for _, name := range users { for _, c := range name { switch c { case 'e', 'E': // 满足该条件给给用户分配金币 distribution[name]++ coins-- case 'i', 'I': distribution[name] += 2 coins -= 2 case 'o', 'O': distribution[name] += 3 coins -= 3 case 'u', 'U': distribution[name] += 4 coins -= 4 } } } left = coins return }
func main() { left := dispatchCoin() // 第二种计算剩余金币方法 计算出map中所有value的和 然后 用金币总数减去 count := 0 for n := range distribution { count += distribution[n] } fmt.Println(count) fmt.Println("剩下:", left, (50 - count)) for k, v := range distribution { fmt.Printf("%s:%d\n", k, v) } }
|