RPN Challenge

RPN
Reverse Polish Notation, a postfix notation.[1]
Postfix Notation
A parenthesis-free notation for forming mathematical expressions in which each operator follows its operands.[2]

On Fri 21/04/00 at 15:04 Daniel Silverstone sent a challenge out to the programmers at CreatureLabs to write the smallest reverse polish notation calculator / filter that they could. The challenge can be read here. My solution (for PocketC), which gets its input from memo "rpn", is shown below:

#define Y s[p];}else if(k==
#define X ){p--;s[p-1]=s[p-1]

int rpn(string d)
{
  int p,i,t,s[99];
  string k;

  while(-1!=(i=strstr(d," ",i+1))){
    k=substr(d,t,i-t);
    if(k== "+" X + 
    Y "-" X - 
    Y "*" X * 
    Y "/" X / s[p];}
    else s[p++]=k;
    t=i+1;
  }
  return s[0];
}

main()
{
  if(mmfind("rpn")){
    mmgetl();
    while(!mmeof())
      puts(rpn(mmgetl()+" ")+"\n");
  }
}

Thad's Homepage (c) Wednesday 17th May 2006 T.Frogley
With thanks to notagoth.org
Valid HTML 4.01!
[ source ]