How to generate a random operator, put it in string, and evaluate the string

huangapple go评论82阅读模式
英文:

How to generate a random operator, put it in string, and evaluate the string

问题

我正在尝试构建一个可以使用随机运算符的方程。

3 x 5 x 8 x 2

其中 x 代表 +、-、/ 或 * 运算符。

第二个问题:如果方程是一个字符串,Golang 能够计算出答案吗?

(这个问题是关于这个问题的:http://www.reddit.com/r/dailyprogrammer/comments/1k7s7p/081313_challenge_135_easy_arithmetic_equations/)

英文:

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

答案1

得分: 3

生成一个随机运算符很简单:

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

(这是使用math/rand包)

按照建议的格式计算简单表达式也很容易。以下是一种简单、低效且脆弱的方法:

expr := strings.Fields("4 * 8 / 2 * 3")
fmt.Printf("%#v\n", 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\n", 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])

(可在 http://play.golang.org/p/pITy4SgXaA 上运行)

如何处理不正确的表达式和非整数,以避免出错,留给读者作为练习。

顺便说一下,这类挑战通常是为开发者提供娱乐的。在这里提问意味着你将这种乐趣转移到其他人身上。

英文:

Generating a random operator is straightforward:

    rand.Seed(int64(time.Now().Unix()))
    op := &quot;+-/*&quot;[rand.Intn(4)]
    fmt.Printf(&quot;%c\n&quot;, 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(&quot;4 * 8 / 2 * 3&quot;)
fmt.Printf(&quot;%#v\n&quot;, 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(&quot;%#v\n&quot;, expr)
}

for _, ops := range []string{&quot;*/&quot;, &quot;+-&quot;} {
	for i := 0; i &lt; len(expr); i++ {
		if strings.Contains(ops, expr[i]) {
			switch expr[i] {
			case &quot;*&quot;: do(i, func(a, b int) int { return a*b })
			case &quot;/&quot;: do(i, func(a, b int) int { return a/b })
			case &quot;+&quot;: do(i, func(a, b int) int { return a+b })
			case &quot;-&quot;: 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.

答案2

得分: 2

Go语言没有像Perl或JavaScript那样的eval函数。因此,如果你想要从字符串中计算一个方程,你需要自己编写代码来解析和计算它。

(这是因为Go是一种编译语言,它不会将编译器的副本放入每个程序中。在解释型语言中添加eval函数要比在编译语言中添加eval函数容易得多。)

英文:

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

huangapple
  • 本文由 发表于 2013年8月25日 03:25:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/18422284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定