Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模範解答 #17

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions lib/sg_romanizer.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
class SgRomanizer
TABLE = [
%w[I II III IV V VI VII VIII IX],
%w[X XX XXX XL L LX LXX LXXX XC],
%w[C CC CCC CD D DC DCC DCCC CM],
%w[M MM MMM],
].freeze

def romanize(arabic)
# write your code here
arabic.digits.filter_map.with_index do |digit, y_pos|
TABLE[y_pos][digit - 1] if digit.nonzero?
end.reverse.join
end

def deromanize(roman)
# write your code here
copied_roman = roman.dup
positions = []
TABLE.reverse.each_with_index do |nums, y_pos|
nums.reverse.each_with_index do |num, x_pos|
positions << [y_pos, x_pos] if copied_roman.delete_prefix!(num)
end
end
positions.sum do |y_pos, x_pos|
max_x_pos = y_pos.zero? ? 3 : 9
10**(TABLE.size - y_pos - 1) * (max_x_pos - x_pos)
end
end
end