package main

import ( "fmt" )

func main() { var nums [4]int var opers []string = []string{"+", "-", "*", "/"} // 四则运算符号 var count int = 0 // 统计有多少种组合方式 var result float64 = 0 // 计算结果 fmt.Println("Please input four numbers (1-13):") fmt.Scanln(&nums[0], &nums[1], &nums[2], &nums[3]) // 输入四个数字 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if j == i { continue } for k := 0; k < 4; k++ { if k == i || k == j { continue } for l := 0; l < 4; l++ { if l == i || l == j || l == k { continue } for m := 0; m < 4; m++ { for n := 0; n < 4; n++ { for o := 0; o < 4; o++ { // 枚举所有情况 if m == i || m == j || m == k || m == l || n == i || n == j || n == k || n == l || o == i || o == j || o == k || o == l { continue } // 计算结果 result = calculate(nums[i], nums[j], nums[k], nums[l], opers[m], opers[n], opers[o]) if result == 24 { count++ fmt.Printf("(%d %s %d) %s (%d %s %d) %s (%d %s %d) = 24\n", nums[i], opers[m], nums[j], opers[n], nums[k], opers[o], nums[l], nums[i], opers[m], nums[j], opers[n], nums[k], opers[o], nums[l]) } } } } } } } } if count == 0 { fmt.Println("No solution!") } }

// 计算结果的函数 func calculate(a, b, c, d int, oper1, oper2, oper3 string) float64 { var result float64 = 0 switch oper1 { case "+": result = float64(a + b) case "-": result = float64(a - b) case "": result = float64(a * b) case "/": if b == 0 { result = 0 } else { result = float64(a) / float64(b) } } switch oper2 { case "+": result += float64(c) case "-": result -= float64(c) case "": result = float64(c) case "/": if c == 0 { result = 0 } else { result /= float64(c) } } switch oper3 { case "+": result += float64(d) case "-": result -= float64(d) case "": result *= float64(d) case "/": if d == 0 { result = 0 } else { result /= float64(d) } } return result }

Go语言实现24点游戏算法

原文地址: http://www.cveoy.top/t/topic/lxn0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录