Ruby script to compare big digits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/local/bin/ruby | |
#********************************************* | |
# 多倍長整数の大小比較 | |
# ( 符号は考慮しない。1桁1配列 ) | |
#********************************************* | |
# | |
class CompareBigDigits | |
D_L = 1000 # 多倍長整数桁数 ( 左辺 ) | |
D_R = 1001 # 多倍長整数桁数 ( 右辺 ) | |
def initialize | |
# 使用する被加減乗除数・加減乗除数を設定(テストなので乱数を使用) | |
@l, @r = Array.new, Array.new | |
rnd_a, rnd_b = Random.new(0), Random.new(1) | |
D_L.times { |_| @l << rand(10) } | |
D_R.times { |_| @r << rand(10) } | |
end | |
# 実処理 | |
def proc_main | |
# 大小比較 | |
s = compare(@l, @r) | |
# 結果出力 | |
display(@l, @r, s) | |
rescue => e | |
raise | |
end | |
private | |
# 大小比較 | |
# | |
# - 引数 : a(多倍長整数・左辺), b(多倍長整数・右辺) | |
# - 返り値 : 1: l > r | |
# 0: l = r | |
# -1: l < r | |
def compare(l, r) | |
# 配列サイズ取得 | |
size_l, size_r = l.size, r.size | |
# 左辺の右辺より大きい部分 | |
if size_l > size_r | |
(size_l - 1).downto(size_r) do |i| | |
return 1 unless l[i] == 0 | |
end | |
end | |
# 右辺の左辺より大きい部分 | |
if size_l < size_r | |
(size_r - 1).downto(size_l) do |i| | |
return -1 unless r[i] == 0 | |
end | |
end | |
# 桁数が同じ場合か、桁数が異なる場合の桁がダブる部分 | |
([size_l, size_r].min - 1).downto(0) do |i| | |
return 1 if l[i] > r[i] | |
return -1 if l[i] < r[i] | |
end | |
# 等しい場合 | |
return 0 | |
rescue => e | |
raise | |
end | |
# 結果出力 | |
def display(l, r, s) | |
# 左辺 | |
puts "[LEFT] =" | |
(D_L - 1).downto(0) do |i| | |
print l[i] | |
print " " if (D_L - i) % 10 == 0 | |
puts if (D_L - i) % 50 == 0 | |
end | |
puts | |
# 右辺 | |
puts "[RIGHT] =" | |
(D_R - 1).downto(0) do |i| | |
print r[i] | |
print " " if (D_R - i) % 10 == 0 | |
puts if (D_R - i) % 50 == 0 | |
end | |
puts | |
# 大小比較結果 | |
puts "[LEFT] #{s == 0 ? "=" : (s > 0 ? ">" : "<")} [RIGHT]" | |
rescue => e | |
raise | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = CompareBigDigits.new | |
# 実処理 | |
obj.proc_main | |
rescue => e | |
$stderr.puts "[#{e.class}] #{e.message}" | |
e.backtrace.each{ |tr| $stderr.puts "\t#{tr}" } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment