Last active
August 29, 2015 14:13
-
-
Save jikkujose/22dcd2a0603af7642171 to your computer and use it in GitHub Desktop.
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
class Base | |
def initialize(alphabets) | |
@alphabets = alphabets | |
end | |
def base | |
@alphabets.length | |
end | |
def to_decimal(number) | |
number.chars.reverse.each_with_index.inject(0) do |decimal, (digit, position)| | |
coiefficient = @alphabets.index(digit) | |
decimal + coiefficient * base**position | |
end | |
end | |
def from_decimal(number) | |
hash = map_coificients(number) | |
hash.keys.max.downto(0).each_with_object('') do |position, output| | |
output << hash[position].to_s | |
end | |
end | |
private | |
def map_coificients(number) | |
current_number = number | |
hash = Hash.new(zero) | |
until current_number == 0 | |
position = Math.log(current_number, base).floor | |
coiefficient = current_number / base**position | |
hash[position] = @alphabets[coiefficient] | |
current_number -= coiefficient * base**position | |
end | |
hash | |
end | |
def zero | |
@alphabets[0] | |
end | |
end | |
class BaseConverter | |
def initialize(source_alphabets, target_alphabets) | |
@source = Base.new source_alphabets | |
@target = Base.new target_alphabets | |
end | |
def convert(number) | |
@target.from_decimal @source.to_decimal number | |
end | |
def self.convert(input, source_alphabets, target_alphabets) | |
new(source_alphabets, target_alphabets).convert input | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment