Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
unixpickle
GitHub Repository: unixpickle/kahoot-hack
Path: blob/master/kahoot/eval.go
10110 views
1
package kahoot
2
3
import (
4
"regexp"
5
"strconv"
6
"strings"
7
)
8
9
var simpleExprRegexp = regexp.MustCompile(`\(([0-9\+\*\s]*)\)`)
10
11
// eval evaluates a mathematical expression, such as:
12
//
13
// ((76 * 21) * (((81 + 4) * 55) + 10))
14
//
15
// This is necessary to obtain session tokens.
16
func eval(expr string) (int64, error) {
17
for {
18
// Evaluate a simple sub-expression.
19
match := simpleExprRegexp.FindStringSubmatch(expr)
20
if match == nil {
21
break
22
}
23
simple := match[1]
24
val, err := evalSimple(simple)
25
if err != nil {
26
return 0, err
27
}
28
valStr := strconv.FormatInt(val, 10)
29
expr = strings.Replace(expr, match[0], valStr, 1)
30
}
31
return evalSimple(expr)
32
}
33
34
// evalSimple evaluates an expression with no nested
35
// parentheses, like
36
//
37
// 23 + 64 + 35 * 35
38
//
39
func evalSimple(expr string) (int64, error) {
40
var sum int64
41
for _, sumTerm := range strings.Split(expr, "+") {
42
product := int64(1)
43
for _, numStr := range strings.Split(sumTerm, "*") {
44
num, err := strconv.ParseInt(strings.TrimSpace(numStr), 10, 64)
45
if err != nil {
46
return 0, err
47
}
48
product *= num
49
}
50
sum += product
51
}
52
return sum, nil
53
}
54
55