aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2019-12-16 15:37:18 +0000
committerGitHub <noreply@github.com>2019-12-16 15:37:18 +0000
commite88fb0046f796c9d9b50910750daacc32c18c3b5 (patch)
tree7b3d2e0e46ebfb14d8741b67b435da2abc730636
parent7febc4d70a3f6488888b16632421062d30be631c (diff)
parent939305e9e0891d24a08a1c29b016592f162b9a38 (diff)
downloadperlweeklychallenge-club-e88fb0046f796c9d9b50910750daacc32c18c3b5.tar.gz
perlweeklychallenge-club-e88fb0046f796c9d9b50910750daacc32c18c3b5.tar.bz2
perlweeklychallenge-club-e88fb0046f796c9d9b50910750daacc32c18c3b5.zip
Merge pull request #1044 from oWnOIzRi/week39
add solution week 039 task 2
-rw-r--r--challenge-039/steven-wilson/perl5/ch-2.pl52
1 files changed, 52 insertions, 0 deletions
diff --git a/challenge-039/steven-wilson/perl5/ch-2.pl b/challenge-039/steven-wilson/perl5/ch-2.pl
new file mode 100644
index 0000000000..d7c5c5c161
--- /dev/null
+++ b/challenge-039/steven-wilson/perl5/ch-2.pl
@@ -0,0 +1,52 @@
+#!/usr/bin/env perl
+# Author: Steven Wilson
+# Date: 2019-12-16
+# Week: 039
+
+# TASK #2
+# Contributed by Andrezgz
+# Write a script to demonstrate Reverse Polish notation(RPN). Checkout
+# the wiki page for more information about RPN.
+# https://en.wikipedia.org/wiki/Reverse_Polish_notation
+
+use strict;
+use warnings;
+use Test::More tests => 2;
+
+my %dt = (
+ '+' => sub { $_[0] + $_[1] },
+ '-' => sub { $_[0] - $_[1] },
+ 'x' => sub { $_[0] * $_[1] },
+ '/' => sub { $_[0] / $_[1] },
+);
+
+ok( evaluate("1 2 +") == 3 );
+ok( evaluate("15 7 1 1 + - / 3 x 2 1 1 + + -") == 5 );
+
+# for each token in the postfix expression:
+# if token is an operator:
+# operand_2 ← pop from the stack
+# operand_1 ← pop from the stack
+# result ← evaluate token with operand_1 and operand_2
+# push result back onto the stack
+# else if token is an operand:
+# push token onto the stack
+# result ← pop from the stack
+
+sub evaluate {
+ my $expression = shift;
+ my @expression = split " ", $expression;
+ my @stack = ();
+ for my $token (@expression) {
+ if ( $token =~ /\d+/ ) {
+ push @stack, $token;
+ }
+ else {
+ my $operand_2 = pop @stack;
+ my $operand_1 = pop @stack;
+ my $result = $dt{$token}->( $operand_1, $operand_2 );
+ push @stack, $result;
+ }
+ }
+ return pop @stack;
+}