Skip to content

Commit

Permalink
Add reverse Polish notation
Browse files Browse the repository at this point in the history
  • Loading branch information
ishanpranav committed Feb 22, 2024
1 parent 93a3330 commit c11a33f
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/rpn.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed under the MIT License.

#include "rpn.h"
#include "rpn_operator.h"

int rpn_evaluate(String tokens[], size_t length)
{
size_t sp = 0;
int* stack = malloc(length * sizeof * stack);

for (size_t i = 0; i < length; i++)
{
if (tokens[i][1] != '\0' || isdigit(tokens[i][0]))
{
stack[sp] = atoi(tokens[i]);
sp++;

continue;
}

stack[sp - 2] = rpn_operator_apply(
tokens[i][0],
stack[sp - 2],
stack[sp - 1]);
sp--;
}

return stack[0];
}
5 changes: 5 additions & 0 deletions lib/rpn.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Licensed under the MIT License.

#include "euler.h"

int rpn_evaluate(String tokens[], size_t length);
16 changes: 16 additions & 0 deletions lib/rpn_operator.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed under the MIT License.

#include "rpn_operator.h"

int rpn_operator_apply(RpnOperator value, int left, int right)
{
switch (value)
{
case RPN_OPERATOR_ADD: return left + right;
case RPN_OPERATOR_SUBTRACT: return left - right;
case RPN_OPERATOR_MULTIPLY: return left * right;
case RPN_OPERATOR_DIVIDE: return left / right;
}

return 0;
}
13 changes: 13 additions & 0 deletions lib/rpn_operator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Licensed under the MIT License.

enum RpnOperator
{
RPN_OPERATOR_ADD = '+',
RPN_OPERATOR_SUBTRACT = '-',
RPN_OPERATOR_MULTIPLY = '*',
RPN_OPERATOR_DIVIDE = '/'
};

typedef enum RpnOperator RpnOperator;

int rpn_operator_apply(RpnOperator value, int left, int right);

0 comments on commit c11a33f

Please sign in to comment.