rpn-converter 0.0.1
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/rpn_converter.rb +47 -0
- metadata +45 -0
@@ -0,0 +1,47 @@
|
|
1
|
+
class RPNConverter
|
2
|
+
|
3
|
+
def infix_to_rpn(exp)
|
4
|
+
@output = ''
|
5
|
+
@stack = []
|
6
|
+
string = exp.gsub(' ', '')
|
7
|
+
string.each_char do |char|
|
8
|
+
case char
|
9
|
+
when /\w/ then @output << char
|
10
|
+
when /\)/ then close_paren
|
11
|
+
when /\(/ then @stack << char
|
12
|
+
else operator(char)
|
13
|
+
end
|
14
|
+
end
|
15
|
+
until @stack.empty? do
|
16
|
+
@output << @stack.pop
|
17
|
+
end
|
18
|
+
@output.gsub(/[()]/, "")
|
19
|
+
end
|
20
|
+
|
21
|
+
def precedence(op)
|
22
|
+
case op
|
23
|
+
when /[+-]/
|
24
|
+
1
|
25
|
+
when /[\*\/]/
|
26
|
+
2
|
27
|
+
when /[()]/
|
28
|
+
0
|
29
|
+
end
|
30
|
+
end
|
31
|
+
|
32
|
+
def close_paren
|
33
|
+
until (@stack.last == '(' ) do
|
34
|
+
@output << @stack.pop
|
35
|
+
end
|
36
|
+
@stack.pop
|
37
|
+
end
|
38
|
+
|
39
|
+
def operator(char)
|
40
|
+
while !@stack.empty? && precedence(char) <= precedence(@stack.last) do
|
41
|
+
@output << @stack.pop
|
42
|
+
end
|
43
|
+
@output << ' ' if @output[@output.length - 1].match /\d/
|
44
|
+
@stack << char
|
45
|
+
end
|
46
|
+
|
47
|
+
end
|
metadata
ADDED
@@ -0,0 +1,45 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: rpn-converter
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.0.1
|
5
|
+
prerelease:
|
6
|
+
platform: ruby
|
7
|
+
authors:
|
8
|
+
- Kelly Stannard
|
9
|
+
autorequire:
|
10
|
+
bindir: bin
|
11
|
+
cert_chain: []
|
12
|
+
date: 2012-07-04 00:00:00.000000000 Z
|
13
|
+
dependencies: []
|
14
|
+
description: Converts from infix to reverse polish notation
|
15
|
+
email: kwstannard@gmail.com
|
16
|
+
executables: []
|
17
|
+
extensions: []
|
18
|
+
extra_rdoc_files: []
|
19
|
+
files:
|
20
|
+
- lib/rpn_converter.rb
|
21
|
+
homepage: http://rubygems.org/gems/rpn-converter
|
22
|
+
licenses: []
|
23
|
+
post_install_message:
|
24
|
+
rdoc_options: []
|
25
|
+
require_paths:
|
26
|
+
- lib
|
27
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
28
|
+
none: false
|
29
|
+
requirements:
|
30
|
+
- - ! '>='
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: '0'
|
33
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
34
|
+
none: false
|
35
|
+
requirements:
|
36
|
+
- - ! '>='
|
37
|
+
- !ruby/object:Gem::Version
|
38
|
+
version: '0'
|
39
|
+
requirements: []
|
40
|
+
rubyforge_project:
|
41
|
+
rubygems_version: 1.8.24
|
42
|
+
signing_key:
|
43
|
+
specification_version: 3
|
44
|
+
summary: A simple RPN converter
|
45
|
+
test_files: []
|