D'oh!

So there was a C# coding contest over at http://www.csharp-home.com/index/tiki-read_article.php?articleId=154 - basically, solve a linear equation for X. I'd idly coded up half the entry for it - the recursive descent parser for the equation syntax - and then got stuck.

My idea was to write a general equation balancer - e.g. if the equation was "2x = 6", balance it to be "x = 6 / 2" then once the variable was isolated on the left side, evaluate the right. I had a few pages worth of algorithms sketched out for the balancing, but then realized that this was too complicated - there must be a simpler solution. So I tabled it, and was busy with other things.

Once the results were announced I went back. D'oh! If you have g(x) = h(x) (and g and h are linear functions of x, i.e. no powers of x other than 1 or 0), then create f(x) = g(x) - h(x), and x = f(0) / (f(0) - f(1)). High-school math I've apparently long forgotten. And was too dumb to search for.

Ah well. Once that simple fact was thrust into my hands, it took about 3 minutes to rejigger my code to solve the problem.

Comments