I have the text content full of expressions like:
a = 1
d = b + c
b = a * c
c = 2 - a
...
This expressions may be written in random order. I can extract each of these expressions and evaluate each of them but I need to find optimal algorithm to avoid circular evaluations like:
a = 1
d = ? (skip)
b = ? (skip)
c = 2 - a = 1
...
d = ? (skip)
b = a * c = 1
...
d = b + c = 2
...
Is there the way "to order" the equations by the involved arguments to avoid extra calculation passes by like:
a = 1
c = 2 - a = 1
b = a * c = 1
d = b + c = 2
...
?
For each expression, create a node in a graph, where the incoming edges are the other expressions it depends upon. Then use a topological sort to determine the evaluation order.
Example:
Expressions:
a = 1
d = b + c
b = a * c
c = 2 - a
Graph nodes:
a()
d(b,c)
b(a,c)
c(a)
Topological sort:
begin
process a
process a's dependencies (none)
output a
mark a as done
process d
process d's dependencies
process b
process b's dependencies
process a (already done)
process c
process c's dependencies
process a (already done)
output c
mark c as done
output b
mark b as done
process c (already done)
output d
mark d as done
process b (already done)
process c (already done)
end
Result:
a c b d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With