Skip to content

Instantly share code, notes, and snippets.

@thedrewbisset
Last active June 9, 2017 23:57
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 thedrewbisset/93168e7c3e3fffa50d54c5e360168e58 to your computer and use it in GitHub Desktop.
Save thedrewbisset/93168e7c3e3fffa50d54c5e360168e58 to your computer and use it in GitHub Desktop.
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