Class: Xqsr3::Containers::FrequencyMap

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Diagnostics::InspectBuilder
Defined in:
lib/xqsr3/containers/frequency_map.rb

Overview

Hash-like class that counts, as the map’s values, the frequencies of elements, as the map’s keys

Constant Summary collapse

ByElement =

Class that provides a Hash[]-like syntax as follows:

fm = FrequencyMap::ByElement[ 'abc', 'def', 'abc', :x, 'x', :y ]

fm.empty? # => false
fm.size   # => 5
fm.count  # => 6
fm['abc'] # => 2
fm['def'] # => 1
fm['ghi'] # => 0
fm['x']   # => 1
fm['y']   # => 0
fm['z']   # => 0
fm[:x]    # => 1
fm[:y]    # => 1
fm[:z]    # => 0
Class.new do

  # Create an instance of Xqsr3::FrequencyMap from an array
  def self.[] *args

    fm = FrequencyMap.new

    args.each { |el| fm << el }

    fm
  end

  private_class_method :new
end

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Diagnostics::InspectBuilder

make_inspect, #make_inspect

Methods included from Enumerable

#collect_with_index, #detect_map, #unique

Constructor Details

#initializeFrequencyMap

Initialises an instance



159
160
161
162
163
# File 'lib/xqsr3/containers/frequency_map.rb', line 159

def initialize

  @elements = {}
  @count    = 0
end

Class Method Details

.[](*args) ⇒ Object

Creates an instance from the given arguments



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/xqsr3/containers/frequency_map.rb', line 95

def self.[] *args

  return self.new if 0 == args.length

  if 1 == args.length

    arg = args[0]

    case arg
    when ::NilClass

      return self.new
    when ::Hash

      fm = self.new
      arg.each do |k, v|

        fm.store k, v
      end
      return fm
    when ::Array

      # accepted forms:
      #
      # 1. Empty array
      # 2. Array exclusively of two-element arrays
      # 3. Array of even number of elements and at every odd index is an integer

      # 1. Empty array

      return self.new if arg.empty?

      # 2. Array exclusively of two-element arrays

      if arg.all? { |el| ::Array === el && 2 == el.size }

        return self.[](::Hash.[]([ *arg ]))
      end

      # 3. Array of even number of elements and at every odd index is an integer

      if (0 == (arg.size % 2)) && arg.each_with_index.select { |el, index| 1 == (index % 2) }.map(&:first).all? { |el| el.kind_of? ::Integer }

        return self.[](::Hash.[](*arg))
      end


      raise ArgumentError, "array parameter not in an accepted form for subscript initialisation"
    else

      return self.[] arg.to_hash if arg.respond_to? :to_hash

      raise TypeError, "given argument is neither a #{::Hash} nor an #{::Array} and does not respond to the to_hash method"
    end

  else

    # treat all other argument permutations as having passed in an array

    return self.[] [ *args ]
  end
end

Instance Method Details

#<<(key) ⇒ Object

Pushes an element into the map, assigning it an initial count of 1

  • Parameters:

    • key The element to insert



169
170
171
172
# File 'lib/xqsr3/containers/frequency_map.rb', line 169

def << key

  push key, 1
end

#==(rhs) ⇒ Object

Compares the instance for equality against rhs

  • Parameters:

    • rhs (nil, ::Hash, FrequencyMap) The instance to compare against

  • Exceptions:

    • ::TypeError if rhs is not of the required type(s)



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/xqsr3/containers/frequency_map.rb', line 181

def == rhs

  case rhs
  when ::NilClass

    return false
  when ::Hash

    return rhs.size == @elements.size && rhs == @elements
  when self.class

    return rhs.count == self.count && rhs == @elements
  else

    raise TypeError, "can compare #{self.class} only to instances of #{self.class} and #{::Hash}, but #{rhs.class} given"
  end

  false
end

#[](key) ⇒ Object

Obtains the count for a given key, or nil if the key does not exist

  • Parameters:

    • key The key to lookup



205
206
207
208
# File 'lib/xqsr3/containers/frequency_map.rb', line 205

def [] key

  @elements[key] || 0
end

#[]=(key, count) ⇒ Object

Assigns a key and a count

  • Parameters:

    • key The key to lookup

    • count (::Integer) The count to lookup

  • Exceptions:

    • ::TypeError if count is not an ::Integer

Raises:

  • (TypeError)


218
219
220
221
222
223
# File 'lib/xqsr3/containers/frequency_map.rb', line 218

def []= key, count

  raise TypeError, "'count' parameter must be of type #{::Integer}, but was of type #{count.class}" unless Integer === count

  store key, count
end

#assoc(key) ⇒ Object

Searches the instance comparing each element with key, returning the count if found, or nil if not



227
228
229
230
# File 'lib/xqsr3/containers/frequency_map.rb', line 227

def assoc key

  @elements.assoc key
end

#clearObject

Removes all elements from the instance



233
234
235
236
237
# File 'lib/xqsr3/containers/frequency_map.rb', line 233

def clear

  @elements.clear
  @count = 0
end

#countObject

The total number of instances recorded



240
241
242
243
# File 'lib/xqsr3/containers/frequency_map.rb', line 240

def count

  @count
end

#defaultObject

Obtains the default value of the instance, which will always be nil



246
247
248
249
# File 'lib/xqsr3/containers/frequency_map.rb', line 246

def default

  @elements.default
end

#delete(key) ⇒ Object

Deletes the element with the given key and its counts

  • Parameters:

    • key The key to delete



255
256
257
258
259
260
# File 'lib/xqsr3/containers/frequency_map.rb', line 255

def delete key

  key_count = @elements.delete key

  @count -= key_count if key_count
end

#dupObject

Duplicates the instance



263
264
265
266
267
268
# File 'lib/xqsr3/containers/frequency_map.rb', line 263

def dup

  fm = self.class.new

  fm.merge! self
end

#eachObject Also known as: each_pair

Calls block once for each element in the instance, passing the element and its frequency as parameters. If no block is provided, an enumerator is returned



273
274
275
276
277
278
279
280
281
# File 'lib/xqsr3/containers/frequency_map.rb', line 273

def each

  return @elements.each unless block_given?

  @elements.each do |k, v|

    yield k, v
  end
end

#each_by_frequencyObject

Enumerates each entry pair - element + frequency - in descending order of frequency

Note: this method is expensive, as it must create a new dictionary and map all entries into it in order to achieve the ordering



304
305
306
307
308
309
310
311
312
313
314
# File 'lib/xqsr3/containers/frequency_map.rb', line 304

def each_by_frequency

  ar = @elements.to_a.sort { |a, b| b[1] <=> a[1] }

  return ar.each unless block_given?

  ar.each do |k, v|

    yield k, v
  end
end

#each_by_keyObject

Enumerates each entry pair - element + frequency - in key order

Note: this method is more expensive than each because an array of keys must be created and sorted from which enumeration is directed



287
288
289
290
291
292
293
294
295
296
297
# File 'lib/xqsr3/containers/frequency_map.rb', line 287

def each_by_key

  sorted_elements = @elements.sort { |a, b| a[0] <=> b[0] }

  return sorted_elements.each unless block_given?

  sorted_elements.each do |k, v|

    yield k, v
  end
end

#each_keyObject

Calls block once for each element in the instance, passing the element. If no block is provided, an enumerator is returned



318
319
320
321
322
323
324
325
326
# File 'lib/xqsr3/containers/frequency_map.rb', line 318

def each_key

  return @elements.each_key unless block_given?

  keys.each do |element|

    yield element
  end
end

#each_valueObject

Calls block once for each element in the instance, passing the count. If no block is provided, an enumerator is returned



332
333
334
335
336
337
338
339
340
# File 'lib/xqsr3/containers/frequency_map.rb', line 332

def each_value

  return @elements.each_value unless block_given?

  keys.each do |element|

    yield @elements[element]
  end
end

#empty?Boolean

Returns true if instance contains no elements; false otherwise

Returns:

  • (Boolean)


343
344
345
346
# File 'lib/xqsr3/containers/frequency_map.rb', line 343

def empty?

  0 == size
end

#eql?(rhs) ⇒ Boolean

Returns true if rhs is an instance of FrequencyMap and contains the same elements and their counts; false otherwise

Returns:

  • (Boolean)


350
351
352
353
354
355
356
357
358
# File 'lib/xqsr3/containers/frequency_map.rb', line 350

def eql? rhs

  case rhs
  when self.class
    return self == rhs
  else
    return false
  end
end

#fetch(key, default = nil, &block) ⇒ Object

Returns the count from the instance for the given element key. If key cannot be found, there are several options: with no other arguments, it will raise a ::KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/xqsr3/containers/frequency_map.rb', line 365

def fetch key, default = nil, &block

  case default
  when ::NilClass, ::Integer
    ;
  else
    raise TypeError, "default parameter ('#{default}') must be of type #{::Integer}, but was of type #{default.class}"
  end

  unless @elements.has_key? key

    return default unless default.nil?

    if block_given?

      case block.arity
      when 0
        return yield
      when 1
        return yield key
      else
        raise ArgumentError, "given block must take a single parameter - #{block.arity} given"
      end
    end

    raise KeyError, "given key '#{key}' (#{key.class}) does not exist"
  end

  @elements[key]
end

#flattenObject

Returns the equivalent flattened form of the instance



397
398
399
400
# File 'lib/xqsr3/containers/frequency_map.rb', line 397

def flatten

  @elements.flatten
end

#has_key?(key) ⇒ Boolean Also known as: include?, key?, member?

Returns true if an element with the given key is in the map; false otherwise

Returns:

  • (Boolean)


404
405
406
407
# File 'lib/xqsr3/containers/frequency_map.rb', line 404

def has_key? key

  @elements.has_key? key
end

#has_value?(value) ⇒ Boolean

Returns true if an element with a count of the given value is in the map; false otherwise

  • Parameters:

    • value (Integer) The value of the count for which to search

  • Exceptions:

    • ::TypeError if value is not an Integer

Returns:

  • (Boolean)


417
418
419
420
421
422
423
424
425
426
427
# File 'lib/xqsr3/containers/frequency_map.rb', line 417

def has_value? value

  case value
  when ::NilClass, ::Integer
    ;
  else
    raise TypeError, "parameter ('#{value}') must be of type #{::Integer}, but was of type #{value.class}"
  end

  @elements.has_value? value
end

#hashObject

A hash-code for this instance



430
431
432
433
# File 'lib/xqsr3/containers/frequency_map.rb', line 430

def hash

  @elements.hash
end

#inspectObject

A diagnostics string form of the instance



438
439
440
441
# File 'lib/xqsr3/containers/frequency_map.rb', line 438

def inspect

  make_inspect show_fields: true
end

#key(count) ⇒ Object

Returns the element that has the given count, or nil if none found

  • Parameters:

    • count (::Integer) The count to lookup

  • Exceptions:

    • ::TypeError if count is not of the required type(s)

Raises:

  • (TypeError)


457
458
459
460
461
462
# File 'lib/xqsr3/containers/frequency_map.rb', line 457

def key count

  raise TypeError, "'count' parameter must be of type #{::Integer}, but was of type #{count.class}" unless Integer === count

  @elements.key count
end

#keysObject

An array of the elements only



467
468
469
470
# File 'lib/xqsr3/containers/frequency_map.rb', line 467

def keys

  @elements.keys
end

#lengthObject Also known as: size

The number of elements in the map



473
474
475
476
# File 'lib/xqsr3/containers/frequency_map.rb', line 473

def length

  @elements.length
end

#merge(fm) ⇒ Object

Returns a new instance containing a merging of the current instance and the fm instance

NOTE: where any element is found in both merging instances the count will be a combination of the two counts

Raises:

  • (TypeError)


485
486
487
488
489
490
491
492
493
494
495
# File 'lib/xqsr3/containers/frequency_map.rb', line 485

def merge fm

  raise TypeError, "parameter must be an instance of type #{self.class}" unless fm.instance_of? self.class

  fm_new = self.class.new

  fm_new.merge! self
  fm_new.merge! fm

  fm_new
end

#merge!(fm) ⇒ Object

Merges the contents of fm into the current instance

NOTE: where any element is found in both merging instances the count will be a combination of the two counts



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# File 'lib/xqsr3/containers/frequency_map.rb', line 501

def merge! fm

  fm.each do |k, v|

    if not @elements.has_key? k

      @elements[k] = v
    else

      @elements[k] += v
    end
    @count += v
  end

  self
end

#push(key, count = 1) ⇒ Object

Pushes the element and count. If the element already exists, count will be added to the existing count; otherwise it will be count

Signature

  • Parameters:

    • key The element key

    • count (Integer) The count by which to adjust

Exceptions

- +::RangeError+ raised if the value of +count+ results in a negative count for the given element
- +::TypeError+ if +count+ is not an +::Integer+

Raises:

  • (TypeError)


531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/xqsr3/containers/frequency_map.rb', line 531

def push key, count = 1

  raise TypeError, "'count' parameter must be of type #{::Integer}, but was of type #{count.class}" unless Integer === count

  initial_count = @elements[key] || 0
  resulting_count = initial_count + count

  raise RangeError, "count for element '#{key}' cannot be made negative" if resulting_count < 0

  if 0 == resulting_count

    @elements.delete key
  else

    @elements[key] = resulting_count
  end
  @count += count

  self
end

#shiftObject

Removes a key-value pair from the instance and return as a two-item array



554
555
556
557
558
559
560
561
# File 'lib/xqsr3/containers/frequency_map.rb', line 554

def shift

  r = @elements.shift

  @count -= r[1] if ::Array === r

  r
end

#store(key, count) ⇒ Object

Causes an element with the given key and count to be stored. If an element with the given key already exists, its count will be adjusted, as will the total count

Return

+true+ if the element was inserted; +false+ if the element was
overwritten

Raises:

  • (TypeError)


572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/xqsr3/containers/frequency_map.rb', line 572

def store key, count

  raise TypeError, "'count' parameter must be of type #{::Integer}, but was of type #{count.class}" unless Integer === count

  old_count = @elements[key] || 0

  @elements.store key, count

  @count += count - old_count

  old_count == 0
end

#to_aObject

Converts instance to an array of [key,value] pairs



586
587
588
589
# File 'lib/xqsr3/containers/frequency_map.rb', line 586

def to_a

  @elements.to_a
end

#to_hObject

Obtains reference to internal hash instance (which must not be modified)



592
593
594
595
# File 'lib/xqsr3/containers/frequency_map.rb', line 592

def to_h

  @elements.to_h
end

#to_hashObject

Obtains equivalent hash to instance



598
599
600
601
# File 'lib/xqsr3/containers/frequency_map.rb', line 598

def to_hash

  @elements.to_hash
end

#to_sObject

A string-form of the instance



604
605
606
607
# File 'lib/xqsr3/containers/frequency_map.rb', line 604

def to_s

  @elements.to_s
end

#valuesObject

An array of all frequencies (without element keys) in the instance



610
611
612
613
# File 'lib/xqsr3/containers/frequency_map.rb', line 610

def values

  @elements.values
end