module VeryAnts::Int

Public Instance Methods

divide(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 15
def divide(x, y, c)
  divide_helper(x, y, c).first
end
minus(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 7
def minus(x, y, c)
  helper(x, -1, y, c)
end
mod(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 19
def mod(x, y, c)
  divide_helper(x, y, c).last
end
mult(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 11
def mult(x, y, c)
  helper(0, x, y, c)
end
plus(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 3
def plus(x, y, c)
  helper(x, 1, y, c)
end

Private Instance Methods

divide_helper(x, y, c) click to toggle source
# File lib/very_ants/int.rb, line 43
def divide_helper(x, y, c)
  raise ZeroDivisionError if y == 0

  chance = Rational(1, c)

  if y < 0
    q, r = divide_helper(x, -y)
    return [-q, r]
  end

  if x < 0
    q, r = divide_helper(-x, y)
    return [-q, 0] if r == 0
    [-real_minus(q, 1), real_minus(y, r)]
  end

  q = 0
  r = x

  (real_mult(c, x.div(y))).times do
    next if rand >= chance
    q = real_plus(q, 1)
    r = real_minus(r, y)
  end

  [q, r]
end
helper(init, incr, y, c) click to toggle source
# File lib/very_ants/int.rb, line 25
def helper(init, incr, y, c)
  chance = Rational(1, c)
  real_mult(c, y).times { init = real_plus(init, incr) if rand < chance }
  init
end
real_minus(x, y) click to toggle source
# File lib/very_ants/int.rb, line 35
def real_minus(x, y)
  real_plus(x, -y)
end
real_mult(x, y) click to toggle source
# File lib/very_ants/int.rb, line 39
def real_mult(x, y)
  (x.to_f * y).to_i
end
real_plus(x, y) click to toggle source
# File lib/very_ants/int.rb, line 31
def real_plus(x, y)
  (x.to_f + y).to_i
end