Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Created November 24, 2011 19:01
Show Gist options
  • Save jnicklas/1392012 to your computer and use it in GitHub Desktop.
Save jnicklas/1392012 to your computer and use it in GitHub Desktop.
This is an implementation of the Roman numeral Kata, inspired by the novel Gadsby by Ernest Vincent Wright. It does not use the letter E.
MAP = [['M', 1000], ['D', 500], ['C', 100], ['L', 50], ['X', 10], ['V',5], ['I',1]]
prv = proc { |i|
t = MAP.map(&:first)
t.zip(t.drop(1)).rassoc(i).first
}
sub = proc { |string|
string.gsub(/(.)?(.)(\2){3}/) { |_|
output = nil
output = $2 + prv[$2] if not $1
output = $2 + prv[$1] if $1 and prv[$2] == $1
output = $1 + $2 + prv[$2] if $1 and prv[$2] != $1
output
}
}
do_it = proc { |arabic|
cons = MAP.find {|c| c.last <= arabic}
arabic == 0 ? "" : cons.first + do_it[arabic - cons.last]
}
catch(:quit) {
loop {
arabic = ARGF.first
throw(:quit) if ! arabic
arabic = arabic.to_i
puts arabic
puts sub[do_it[arabic]]
# 1 last thing:
ARGF.first
}
}
ruby roman.rb spc.txt | diff -u spc.txt - && printf 'Good!\n'
grep -i e roman.rb
1
I
2
II
7
VII
9
IX
40
XL
140
CXL
3999
MMMCMXCIX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment