Comment

Comment by JaumeGreen

We could give weight to operators. Operators that are heavier go further down the three (have precedence) while the lighter ones float.

1+2*3^(4+1)+2/3

We start the evaluation with 1+, the chain would be on (+) for now.

       (+) <
       / 
     (1) 
The next operator is (*), and because this one is heavier it falls down, bringing 2 with it.

       (+) 
       / \
     (1) (*) <
         /
        (2)
Now checking the next operator (^), once again heavier, goes down the three.

       (+) 
       / \
     (1) (*)
         / \
       (2) (^) <
           /
         (3)
The next operation is between parenthesis, that takes precedence and goes down, but the pointer comes up after the operation has taken place.

       (+) 
       / \
     (1) (*)
         / \
       (2) (^) <
           / \
         (3) (+)
             / \
            (4) (1)
    
Next operation is (+), this one floats, and as it's the same weight at the root it doesn't matter its relationship with it, so we put it higher.

        (+) <
        / \
       (+) 2
       / \
     (1) (*)
         / \
       (2) (^)
           / \
         (3) (+)
             / \
            (4) (1)
Finally we got the division, which is heavier again.

         (+)
         /  \
       (+)   (/)
       / \    / \
     (1) (*) (2) (3)
         / \
       (2) (^)
           / \
         (3) (+)
             / \
            (4) (1)
Did this on the fly, so it might have edge cases, but it works well as a starting point.
parent JaumeGreen 1 month ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton