Pergunta de entrevista da empresa Tesla

write a command-line program to evaluate a set of equations. Like: a=b+4 b=c+d d=4 c=3+2

Respostas da entrevista

Sigiloso

16 de fev. de 2018

This can be a simple as a toposort, or as hard as a Gaussian Substitution depending on the requirements

2

Sigiloso

14 de dez. de 2018

import ( "os" "fmt" "strings" "strconv" ) func calc(equations map[byte]string, key byte) int { expr := strings.Split(equations[key], "+") sum := 0 for _, ex := range expr { val, err := strconv.Atoi(ex) if err == nil { sum += val } } return sum } func resolve(equations map[byte]string, key byte) string { buf := []byte(equations[key]) for i:= 0; i= 'a' && v <= 'z' { _, ok := equations[v] if ok { equations[v] = resolve(equations, v) buf = append(buf[0:i], append([]byte(equations[v]), buf[i+1:]...)...) } } } return string(buf) } func main() { args := os.Args[1:] equations := make(map[byte]string, len(args)) for _, arg := range args { parts := strings.Split(arg, "=") equations[parts[0][0]] = parts[1] } for key, _ := range equations { equations[key] = resolve(equations, key) fmt.Printf("%c=%d\n", key, calc(equations, key)) } }

Sigiloso

21 de out. de 2017

C++ code for a topological sort