Last active
June 9, 2017 23:57
-
-
Save thedrewbisset/93168e7c3e3fffa50d54c5e360168e58 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
module DecimalRebase | |
# Breaks the decimal down into increments of the difference of the increment and the base number until the result is zero | |
# The resulting increments are accumulated and when the rebased value reaches zero, their modulos are mapped, reversed, and converted | |
# | |
# Example: | |
# value: 75 converted to base: 8 | |
# rebase(75, 8) | |
# 75 / 8 = 9 => rebase(9, 8, [75]) | |
# 9 / 8 = 1 => rebase(1, 8, [75,9]) | |
# 1 / 8 = 0 => rebase(0, 8, [75,9,1] | |
# [75,9,1] => [3,1,1] => [1,1,3] => 113 => '113' => 113 | |
extend self | |
def call(decimal, base, accumulator = []) | |
if decimal > 0 | |
accumulator.push(decimal) | |
rebase(decimal / base, base, accumulator) | |
else | |
accumulator.map {|n| n % base }.join.reverse.to_i | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment