Sha256: 41301078d8a75dfb3165664c251226296149435d6138b97fd661410e0b3ac09d

Contents?: true

Size: 1.03 KB

Versions: 11

Compression:

Stored size: 1.03 KB

Contents

module MoreMath
  module CantorPairingFunction

    module_function

    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

    def self.cantor_pairing_inv_f(z)
      z * (z + 1) / 2
    end

    def self.cantor_pairing_inv_q(z)
      v = 0
      while cantor_pairing_inv_f(v) <= z
        v += 1
      end
      v - 1
    end

    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
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
more_math-1.3.0 lib/more_math/cantor_pairing_function.rb
more_math-1.2.2 lib/more_math/cantor_pairing_function.rb
more_math-1.2.1 lib/more_math/cantor_pairing_function.rb
more_math-1.2.0 lib/more_math/cantor_pairing_function.rb
more_math-1.1.0 lib/more_math/cantor_pairing_function.rb
more_math-1.0.2 lib/more_math/cantor_pairing_function.rb
more_math-1.0.1 lib/more_math/cantor_pairing_function.rb
more_math-1.0.0 lib/more_math/cantor_pairing_function.rb
more_math-0.4.0 lib/more_math/cantor_pairing_function.rb
more_math-0.3.3 lib/more_math/cantor_pairing_function.rb
more_math-0.3.2 lib/more_math/cantor_pairing_function.rb