16
\$\begingroup\$

We've had a lot of challenges on differentiation and integration, but none on just solving related rates problems. So in this challenge, you will get a bunch of derivatives (They will be numeric, not in terms of any variables) and have to find another derivative.

The input will come in a newline separated list of equations, in the form dx/dt = 4. There can be decimals and negatives.

The input will end with one differential, the one you will have to find. You can assume there will always be enough information to find it, butt there may also be excess information.

You may also have to consider the derivative of the inverse function, e.g. if you have dy/dx = 3, you also know that dx/dy = 1/3.

Your output will be in the form dy/dt = 6. All the whitespace, etc. has to be the same. Assume all variables are always one letter (They can be uppercase, and they can be d).

This is , so shortest code in bytes wins!

Test Cases

dy/dx = 4
dx/dt = 5
dy/dt

answer: dy/dt = 20

dy/dx = -3
dt/dx = 3
dy/dt

answer: dy/dt = -1

dA/dt = 4
dA/dC = 2
dC/dr = 6.28
dr/dt

answer: dr/dt = 0.3184713375796178

dx/dy = 7
dx/dt = 0
dy/dt

answer: dy/dt = 0
\$\endgroup\$
15
  • \$\begingroup\$ Is the output "answer: dx/dt = .318" or just "dx/dt = .318"? \$\endgroup\$
    – GamrCorps
    Commented Dec 29, 2015 at 20:40
  • \$\begingroup\$ @GamrCorps the latter. \$\endgroup\$
    – Maltysen
    Commented Dec 29, 2015 at 20:47
  • 2
    \$\begingroup\$ Can we use built-in equation solvers? \$\endgroup\$ Commented Dec 29, 2015 at 21:26
  • 3
    \$\begingroup\$ I have a feeling answers will treat d_/d_ as a ratio and that makes me sad \$\endgroup\$
    – Arcturus
    Commented Dec 29, 2015 at 21:39
  • \$\begingroup\$ @MartinBüttner yes, but not builtin differential equation solvers. \$\endgroup\$
    – Maltysen
    Commented Dec 29, 2015 at 22:18

1 Answer 1

3
\$\begingroup\$

Python - 278 275

No one else has done this yet, so I thought I'd submit this, even though it isn't golfed very well yet.

a={}
e={}
k=input
i=k()
while"="in i:
 b,d=i.split(" =");b,c=b.split("/");d=float(d)
 if d:a[b]=a.get(b,[])+[[c,1/d]]
 a[c]=a.get(c,[])+[[b,d]];i=k()
i=i.split("/")
def f(x):
 for j in a.get(x,[]):
  if j[0] not in e:e[j[0]]=e[x]*j[1];f(j[0])
e[i[1]]=1
f(i[1])
print(e[i[0]])

Here it is partially ungolfed:

a={}
e={}
i=input()
while "=" in i:
 b,d=i.split(" =")
 b,c=b.split("/")
 d=float(d)
 if d:a[b]=a.get(b,[])+[[c,1/d]]
 a[c]=a.get(c,[])+[[b,d]]
 i=input()
i=i.split("/")
def f(x):
 for j in a.get(x,[]):
  if j[0] not in e:e[j[0]]=e[x]*j[1];f(j[0])
e[i[1]]=1
f(i[1])
print(e[i[0]])

Three bytes were saved by Thomas Kwa.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.