Class: WalkerMethod

Inherits:
Object
  • Object
show all
Defined in:
lib/walker_method.rb,
lib/walker_method/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keys, weights) ⇒ WalkerMethod

Returns a new instance of WalkerMethod.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/walker_method.rb', line 6

def initialize(keys, weights)
  self.keys = keys
  self.weights = weights
  self.sumw = weights.reduce(&:+).to_f
  self.prob = []
  self.inx = []
  self.length = weights.length
  short = []
  long = []
  weights.each do |w|
    inx << -1
    prob << w * length / sumw
  end

  prob.each.with_index do |p, index|
    short << index if p < 1
    long << index if p > 1
  end

  while short.length > 0 && long.length > 0
    j = short.pop
    k = long[-1]
    inx[j] = k
    prob[k] -= (1 - prob[j])
    if prob[k] < 1
      short << k
      long.pop
    end
  end

  def random
    u = rand
    j = (rand * length).to_i
    if u <= prob[j]
      keys[j]
    else
      keys[inx[j]]
    end
  end
end

Instance Attribute Details

#inxObject

Returns the value of attribute inx.



4
5
6
# File 'lib/walker_method.rb', line 4

def inx
  @inx
end

#keysObject

Returns the value of attribute keys.



4
5
6
# File 'lib/walker_method.rb', line 4

def keys
  @keys
end

#lengthObject

Returns the value of attribute length.



4
5
6
# File 'lib/walker_method.rb', line 4

def length
  @length
end

#probObject

Returns the value of attribute prob.



4
5
6
# File 'lib/walker_method.rb', line 4

def prob
  @prob
end

#sumwObject

Returns the value of attribute sumw.



4
5
6
# File 'lib/walker_method.rb', line 4

def sumw
  @sumw
end

#weightsObject

Returns the value of attribute weights.



4
5
6
# File 'lib/walker_method.rb', line 4

def weights
  @weights
end

Instance Method Details

#randomObject



36
37
38
39
40
41
42
43
44
# File 'lib/walker_method.rb', line 36

def random
  u = rand
  j = (rand * length).to_i
  if u <= prob[j]
    keys[j]
  else
    keys[inx[j]]
  end
end