Sunday, December 23, 2018

Shunting algorithm is a sorting algorithm

Below is the code I use, it is strictly Towers of Hanoi with three posts, Oper, Input and Output. Oper post is the middle post. This mostly works, not completely tested. It relies on prec, the affinity for the Output post, bring set properly. correct. The precedence is equivalent to the ring size in the Towers f Hanoi. Not much code to unfold a complex parenthesis laden expression. What I have is much simpler than the commented algorithm from Wiki. Instead of left,right associativity, I have the least significant bit of precedence, use that. Instead of functions special property, I just give them the second to lowest.  Parenthesis have the lowest.

int shunt(PStack input) {
Val datum;
char *test;
int count=0;
int i;
do {
datum = pull(input);
TokeBase++;
if(datum.s[0] == ';') break;
if(datum.s[0] == ')') count--;
if(datum.s[0] == '(') count++;
if(Oper.fill)
while((prec(datum.s) < prec(top(&Oper).s) ) )
lift(&Output,pop(&Oper));
push(&Oper,datum);
} while(count);
while(Oper.fill) {
datum= pop(&Oper);
if((datum.s[0] != '(') && (datum.s[0] != ')'))
lift(&Output,datum);
}
}


The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower[1] and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

No comments: