dorkahemp972157683 2013-08-24 19:25
浏览 71
已采纳

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

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/ )

  • 写回答

2条回答 默认 最新

  • doucai9270 2013-08-24 20:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本