Skip to content

Instantly share code, notes, and snippets.

@jikkujose
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jikkujose/22dcd2a0603af7642171 to your computer and use it in GitHub Desktop.
Save jikkujose/22dcd2a0603af7642171 to your computer and use it in GitHub Desktop.
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