For a simple linear equation with an arbitrarily complex input stream, e.g. 2+3x+7(x+27)-6 you can probably do it with a minimum of conditionals. The hard part is writing a parser, but it's also entertaining. How I might do it, based on not spending much time on it and not having done one in a while is:

a) Write a parser that splits on the equal sign and multiplies everything out to eliminate parentheses, so my expression above would be 2+3x+7x+189-6.

b) do a second pass where you look at each term and add it into a pair of accumulators, one for the constants and one for the slopes. When you process the righthand side, multiply everything by -1 before you add it.

Now you have something like 3235643596 in the slope accumulator (corresponding to the "x" terms) and 998396 in the constant accumulator. Do a simple division of one by the other and you're done.

Writing the parser is the hard part, and it shouldn't be that hard for your case (you should be able to do it with a little recursive chunk of code)


In reply to Re: How would you solve a user-inputted simple one-variable Linear Equation by bitingduck
in thread How would you solve a user-inputted simple one-variable Linear Equation by nat47

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.