Created
March 12, 2016 01:09
-
-
Save durrellchamorro/ffae838d2f29cf4ca886 to your computer and use it in GitHub Desktop.
Trinary
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
class Trinary | |
def initialize(string) | |
@trinary_number = string | |
end | |
def to_decimal | |
return 0 if contains_any_non_digit? | |
numbers_paired_with_powers.map do |pair| | |
pair[0].to_i * 3**pair[1] | |
end.inject(:+) | |
end | |
private | |
def contains_any_non_digit? | |
@trinary_number =~ /\D/ | |
end | |
def numbers_paired_with_powers | |
powers = 0..@trinary_number.size - 1 | |
@trinary_number.chars.zip(powers.to_a.reverse) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment