Class: Tsumetogi::PageNum

Inherits:
Object
  • Object
show all
Defined in:
lib/tsumetogi/page_num.rb

Constant Summary collapse

MAX =
0x100000000
Infinity =
PageNum.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj = nil) ⇒ PageNum

Returns a new instance of PageNum.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tsumetogi/page_num.rb', line 22

def initialize(obj = nil)
  case obj
  when Array, nil
    @digits = obj
  when String
    @digits = obj.split("_").map(&:hex)
  when Numeric
    @digits = [obj]
  when PageNum
    @digits = obj.digits.dup
  else
    raise "Unknown object was given to create a PageNum object: #{obj.inspect}"
  end
end

Class Method Details

.lerp(x, y, n) ⇒ Object

Interpolate n points between x and y



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/tsumetogi/page_num.rb', line 10

def self.lerp(x, y, n)
  x0 = [x, y].min
  x1 = [x, y].max
  dx = (x1 - x0) / (n + 1)

  ret = n.times.map do |i|
    x0 + dx * (i + 1)
  end
  ret.reverse! if x0 != x
  ret
end

Instance Method Details

#*(n) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/tsumetogi/page_num.rb', line 73

def *(n)
  carry = 0
  ret = self.digits.reverse.map do |d|
    carry, mul = (carry + d * n).divmod(MAX)
    mul
  end

  if carry.zero?
    self.class.new(ret.reverse)
  else
    Infinity
  end
end

#+(other) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/tsumetogi/page_num.rb', line 45

def +(other)
  carry = 0
  ret = self.reverse_each_other(other).map do |a, b|
    carry, sum = (carry + a + b).divmod(MAX)
    sum
  end

  if carry.zero?
    self.class.new(ret.reverse)
  else
    Infinity
  end
end

#-(other) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/tsumetogi/page_num.rb', line 59

def -(other)
  borrow = 0
  ret = self.reverse_each_other(other).map do |a, b|
    borrow, diff = (borrow + a - b).divmod(MAX)
    diff
  end

  if borrow.zero?
    self.class.new(ret.reverse)
  else
    self.class.new
  end
end

#/(n) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/tsumetogi/page_num.rb', line 87

def /(n)
  decimal = 0
  ret = self.digits.map do |d|
    div = (MAX * decimal + d).quo(n)
    decimal = div - div.to_i
    div.to_i
  end

  ret << MAX * decimal if decimal.nonzero?
  self.class.new(ret)
end

#<=>(other) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/tsumetogi/page_num.rb', line 37

def <=>(other)
  self.each_other(other) do |a, b|
    ret = a <=> b
    return ret if ret.nonzero?
  end
  0
end

#to_s(size = nil) ⇒ Object



99
100
101
102
103
104
105
106
107
# File 'lib/tsumetogi/page_num.rb', line 99

def to_s(size = nil)
  self.compact.padding(size)

  hexes = self.digits.map do |d|
    "%08x" % d
  end

  hexes.join('_')
end