如何生成一个随机运算符,将其放入字符串中,并评估该字符串

I'm trying to build an equation that takes random operators.

3 x 5 x 8 x 2

where x represents either a +, -, / * operator.

2nd question: if the equation is a string, can golang evaluate the answer?

(this question is for this problem http://www.reddit.com/r/dailyprogrammer/comments/1k7s7p/081313_challenge_135_easy_arithmetic_equations/ )

Generating a random operator is straightforward:

    rand.Seed(int64(time.Now().Unix()))
    op := "+-/*"[rand.Intn(4)]
    fmt.Printf("%c
", op)

(that's math/rand)

Evaluating simple expressions in the format suggested is also easy. Here is a simplistic, inefficient, and fragile way of doing it:

expr := strings.Fields("4 * 8 / 2 * 3")
fmt.Printf("%#v
", expr)

do := func(i int, op func(a, b int) int) {
    ai, err := strconv.Atoi(expr[i-1])
    check(err)
    bi, err := strconv.Atoi(expr[i+1])
    check(err)
    expr[i-1] = strconv.Itoa(op(ai, bi))
    expr = append(expr[:i], expr[i+2:]...)
    fmt.Printf("%#v
", expr)
}

for _, ops := range []string{"*/", "+-"} {
    for i := 0; i < len(expr); i++ {
        if strings.Contains(ops, expr[i]) {
            switch expr[i] {
            case "*": do(i, func(a, b int) int { return a*b })
            case "/": do(i, func(a, b int) int { return a/b })
            case "+": do(i, func(a, b int) int { return a+b })
            case "-": do(i, func(a, b int) int { return a-b })
            }
            i -= 2
        }
    }
}

fmt.Println(expr[0])

(runnable on http://play.golang.org/p/pITy4SgXaA)

Making it not break down with improper expressions and handle non-ints is left as an exercise for the reader.

As a side note, these kinds of challenges are generally meant as entertainment for the developer. Asking here means you're transferring that fun to somebody else.

Go does not have an eval function like Perl or JavaScript. So if you want to evaluate an equation from a string, you will need to write the code to parse it and evaluate it yourself.

(The reason for this is that Go is a compiled language, and it does not put a copy of the compiler into every program. It is much easier to add an eval function to an interpreted language than to a compiled one.)