Last active
August 29, 2016 22:00
-
-
Save evmorov/7a90228f0eba5f2dee331408ad618856 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 smallest(num) | |
"base #{smallest_base(num)} => #{to_dec(num, smallest_base(num))}" | |
end | |
def all_bases(num) | |
(smallest_base(num).to_i..16).map { |base| "base #{base} => #{to_dec(num, base)}" }.join("\n") | |
end | |
def to_dec(num, base) | |
num.to_s.chars.reverse.map.with_index { |n, i| to_digit(n) * base**i }.reduce(:+) | |
end | |
private | |
def smallest_base(num) | |
num.to_s.chars.map { |n| to_digit(n) }.max + 1 | |
end | |
def to_digit(letter) | |
letter =~ /[[:alpha:]]/ ? letter.ord - 'a'.ord + 10 : letter.to_i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment