Module: MoreMath::CantorPairingFunction
- Defined in:
- lib/more_math/cantor_pairing_function.rb
Class Method Summary collapse
- .cantor_pairing(*xs) ⇒ Object
- .cantor_pairing_inv(c, n = 2) ⇒ Object
- .cantor_pairing_inv_f(z) ⇒ Object
- .cantor_pairing_inv_q(z) ⇒ Object
Class Method Details
.cantor_pairing(*xs) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/more_math/cantor_pairing_function.rb', line 6 def cantor_pairing(*xs) if xs.size == 1 and xs.first.respond_to?(:to_ary) xs = xs.first.to_ary end case xs.size when 0, 1 raise ArgumentError, "at least two arguments are required" when 2 x, y, = *xs (x + y) * (x + y + 1) / 2 + y else cantor_pairing(cantor_pairing(*xs[0..1]), *xs[2..-1]) end end |
.cantor_pairing_inv(c, n = 2) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/more_math/cantor_pairing_function.rb', line 33 def cantor_pairing_inv(c, n = 2) raise ArgumentError, "n is required to be >= 2" unless n >= 2 result = [] begin q = CantorPairingFunction.cantor_pairing_inv_q(c) y = c - CantorPairingFunction.cantor_pairing_inv_f(q) x = q - y result.unshift y c = x n -= 1 end until n <= 1 result.unshift x end |
.cantor_pairing_inv_f(z) ⇒ Object
21 22 23 |
# File 'lib/more_math/cantor_pairing_function.rb', line 21 def self.cantor_pairing_inv_f(z) z * (z + 1) / 2 end |
.cantor_pairing_inv_q(z) ⇒ Object
25 26 27 28 29 30 31 |
# File 'lib/more_math/cantor_pairing_function.rb', line 25 def self.cantor_pairing_inv_q(z) v = 0 while cantor_pairing_inv_f(v) <= z v += 1 end v - 1 end |