Module: BalancedTernaryInteger

Defined in:
lib/balanced_ternary_integer.rb,
lib/balanced_ternary_integer/version.rb,
ext/balanced_ternary_integer/balanced_ternary_integer.c

Constant Summary collapse

VERSION =
"0.2.1"

Class Method Summary collapse

Class Method Details

.from_int(number) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
# File 'lib/balanced_ternary_integer.rb', line 6

def from_int(number)
  raise ArgumentError, "Integer expected, got #{number.class}" unless number.instance_of?(Integer)

  digits = ''
  begin
    quotient, modulus = number.divmod(3)
    digits.prepend(modulus == 2 ? 'T' : modulus.to_s)
    number = modulus == 2 ? quotient + 1 : quotient
  end until number.zero?
  digits
end

.to_int(rb_string) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'ext/balanced_ternary_integer/to_int.c', line 16

VALUE rb_balanced_ternary_integer_to_int(VALUE self, VALUE rb_string) {
    Check_Type(rb_string, T_STRING);  // raise TypeError (wrong argument type Integer (expected String))

    char *chars = RSTRING_PTR(rb_string);
    long len = RSTRING_LEN(rb_string);
    VALUE exp = INT2FIX(1);
    VALUE result = INT2FIX(0);
    short digit;

    for (int i = len - 1; i >= 0; i--) {
        digit = INT2NUM(char_to_num(chars[i]));
        result = rb_funcall(result, '+', 1, rb_funcall(digit, '*', 1, exp)); // result += digit * exp
        exp = rb_funcall(exp, '*', 1, INT2FIX(3)); // множитель (1, 3, 9 и тд)
    }
    return result;
}