Class: ConlangWordGenerator::SymbolSet

Inherits:
Object
  • Object
show all
Defined in:
lib/conlang/symbolset.rb

Instance Method Summary collapse

Constructor Details

#initializeSymbolSet

Returns a new instance of SymbolSet.



7
8
9
10
# File 'lib/conlang/symbolset.rb', line 7

def initialize
  @pairs = []
  @weight_accum = 0
end

Instance Method Details

#+(other) ⇒ Object

Make Symbolset class appendable



51
52
53
# File 'lib/conlang/symbolset.rb', line 51

def +(other)
  Append.new(self, other)
end

#add_pair(symbol, weight) ⇒ Object

Add new symbol with its probability into the set



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/conlang/symbolset.rb', line 13

def add_pair(symbol, weight)
  unless weight > 0 and weight < 100
    raise LangSyntaxError, "Weight of symbol '#{symbol}' must be " +
                           "a value between 1 and 99, inclusive."
  end

  # Insert new pair in the sorted array of pairs

  inserted = false
  @pairs.each_index do |index|
    if @pairs[index][1] > weight
      @pairs.insert(index, [symbol, weight])
      inserted = true
      break
    end
  end

  # Insert at the end, if requiered

  @pairs += [[symbol, weight]] unless inserted
  
  # Sum weights

  @weight_accum += weight
end

#sampleObject

Get a random symbol from the set



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/conlang/symbolset.rb', line 37

def sample
  random = rand(@weight_accum)

  accum = 0
  @pairs.each_index do |index|
    accum += @pairs[index][1]

    if accum > random
      return @pairs[index][0]
    end
  end
end