KEY NOT FOUND: coverImgAlt
Logo
See All Photos

Tesla

Engaged Employer

Tesla

Add an Interview

Interview Question

Software Engineer Interview

-

Tesla

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

AnswerAdd Tags

Interview Answers

3 Answers

2

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

Anonymous on

0

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

Anonymous on

0

C++ code for a topological sort

Anonymous on

Add Answers or Comments

To comment on this, Sign In or Sign Up.

Tesla Careers

Cover image for Tesla

Tesla’s mission is to accelerate the world’s transition to sustainable energy. Burning fossil fuels for transportation, heat and...More

  • Products
  • Culture
  • Benefits and Perks
  • Students
This is the employer's chance to tell you why you should work for them. The information provided is from their perspective.