3

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
...

?

4

1 回答 1

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
于 2012-09-23T04:25:57.303 回答