Go language function exercise - divide gold coins

Go language function exercise - divide gold coins


Topic source: https://www.liwenzhou.com/posts/Go/09_function/


Title description:

You have 50 gold coins that need to be distributed among the following people: Matthew, Sarah, Augustus, Heidi, Emilie, Peter, Giana, Adriano, Aaron, Elizabeth.
The distribution rules are as follows:
a. One gold coin for every 'e' or 'E' in
the name b. Two gold coins for every 'i' or 'I' in the name
c. One gold coin for every one in the name 3 gold coins for 'o' or 'O'
d: 4 gold coins for each 'u' or 'U' in the name Write
a program to calculate how many gold coins each user gets and how many gold coins are left in the end?
The program structure is as follows, please implement the 'dispatchCoin' function

var (
	coins = 50
	users = []string{
		"Matthew", "Sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth",
	}
	distribution = make(map[string]int, len(users))
)

func main() {
	left := dispatchCoin()
	fmt.Println("剩下:", left)
}

Based on the program structure mentioned in the exercise, the answer is as follows:

var (
	coins = 50
	users = []string{
    
    
		"Matthew", "Sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth",
	}
	distribution = make(map[string]int,len(users))
)
//首相要将字符切片中的数据添加到map中
func dispatchCoin() int {
    
    
    //因为不需要字符切片的下标值,所以使用匿名变量来接收下标值
	for _,v := range users{
    
    
        //将字符切片的值添加到map中做键,将键对应的值赋值为0
		distribution[v] = 0
        //再利用循环遍历map中的键,用来判断
		for _,value := range v{
    
    
            //在switch使用map中的键当做判断条件
			switch value {
    
    
			case 'e', 'E':
				distribution[v] ++
				coins --
			case 'i', 'I':
				distribution[v] += 2
				coins -= 2
			case 'o', 'O':
				distribution[v] += 3
				coins -= 3
			case 'u', 'U':
				distribution[v] += 4
				coins -= 4
			}
		}
	}
    //循环打印出map中存在的值
	for name,value := range distribution{
    
    
		fmt.Println(name,value)
	}	
	return coins
}

func main(){
    
    
	left := dispatchCoin()
	fmt.Println("剩下:",left)
	// fmt.Println(distribution)
}

The above is the code for the gold coin exercise.

Introduced with comments in the code, please point out if there are any mistakes!

Guess you like

Origin blog.csdn.net/weixin_46435420/article/details/118339782