Module: Bases::Algorithms
- Defined in:
- lib/bases/algorithms.rb
Overview
This module encapsulates the practical algorithms used to change bases.
Class Method Summary collapse
-
.convert_from_base(digits_ary, source_base) ⇒ Integer
Convert a value in a source base to an integer in base 10.
-
.convert_to_base(value, new_base) ⇒ Array<String>
The common base conversion algorithm, which converts a number in base 10 (
value) to its value in basenew_base.
Class Method Details
.convert_from_base(digits_ary, source_base) ⇒ Integer
Convert a value in a source base to an integer in base 10.
32 33 34 35 36 37 38 39 |
# File 'lib/bases/algorithms.rb', line 32 def self.convert_from_base(digits_ary, source_base) # The numeric base is the number of digits in the source base. numeric_base = source_base.count digits_ary.reduce(0) do |acc, digit| source_base.find_index(digit) + numeric_base * acc end end |
.convert_to_base(value, new_base) ⇒ Array<String>
The common base conversion algorithm, which converts a number in base 10
(value) to its value in base new_base.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/bases/algorithms.rb', line 11 def self.convert_to_base(value, new_base) # Return early if the is 0, as it is the first digit of the base array. return [new_base.first] if value == 0 result = [] numeric_base = new_base.count while value > 0 remainder = value % numeric_base value /= numeric_base result.unshift(new_base[remainder]) end result end |