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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| package main
import ( "fmt" "strconv" )
func MakeTwentyFour(nums []int) (expr string, found bool) { _assertEqual(4, len(nums))
var fnums []float64 var exprs []string
for _, num := range nums { fnums = append(fnums, float64(num)) exprs = append(exprs, strconv.Itoa(num)) }
found, expr = solve(fnums, exprs) return }
func solve(nums []float64, exprs []string) (found bool, solution string) { _assertEqual(true, len(nums) >= 1) _assertEqual(len(nums), len(exprs))
if len(nums) == 1 { return nums[0] == 24, exprs[0] }
for i := 0; i < len(nums); i++ { for j := 0; j < len(nums); j++ { if i == j { continue }
nextExprs := make([]string, 0, len(exprs)-1) nextNums := make([]float64, 0, len(nums)-1) for k := 0; k < len(nums); k++ { if k == i || k == j { continue } nextExprs = append(nextExprs, exprs[k]) nextNums = append(nextNums, nums[k]) }
for _, op := range []byte{'+', '-', '*', '/'} { var num float64 switch op { case '+': num = nums[i] + nums[j] case '-': num = nums[i] - nums[j] case '*': num = nums[i] * nums[j] case '/': num = nums[i] / nums[j] } nextNums = append(nextNums, num) nextExprs = append(nextExprs, fmt.Sprintf("(%s%c%s)", exprs[i], op, exprs[j]))
if found, solution = solve(nextNums, nextExprs); found { return } nextNums = nextNums[:len(nextNums)-1] nextExprs = nextExprs[:len(nextExprs)-1] } } } return false, "" }
func _assertEqual(expected, actual interface{}) { if expected != actual { panic("assertion failed") } }
func main() { cases := [][]int{ {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}, {5, 5, 5, 5}, {6, 6, 6, 6}, {3, 3, 7, 7}, {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}, {5, 6, 7, 8}, {6, 7, 8, 9}, {7, 8, 9, 10}, {3, 8, 4, 5}, {3, 3, 7, 9}, {13, 3, 13, 1}, {11, 3, 7, 2}, }
for _, nums := range cases { expr, found := MakeTwentyFour(nums) if !found { fmt.Printf("%v: not found\n", nums) } else { fmt.Printf("%v: %s\n", nums, expr) } } }
|