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



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

def initialize

  @elements  =   {}
  @count = 0
end

Class Method Details

.[](*args) ⇒ Object

Creates an instance from the given arguments



94
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
# File 'lib/xqsr3/containers/frequency_map.rb', line 94

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



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

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)



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

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



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

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)


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

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



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

def assoc key

  @elements.assoc key
end

#clearObject

Removes all elements from the instance



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

def clear

  @elements.clear
  @count = 0
end

#countObject

The total number of instances recorded



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

def count

  @count
end

#defaultObject

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



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

def default

  @elements.default
end

#delete(key) ⇒ Object

Deletes the element with the given key and its counts

  • Parameters:

    • key The key to delete



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

def delete key

  key_count = @elements.delete key

  @count -= key_count if key_count
end

#dupObject

Duplicates the instance



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

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



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

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



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/xqsr3/containers/frequency_map.rb', line 299

def each_by_frequency

  tm = {}
  @elements.each do |element, frequency|

    tm[frequency] = []  unless tm.has_key?(frequency)

    tm[frequency].push element
  end

  keys = tm.keys.sort.reverse
  keys.each do |frequency|

    elements = tm[frequency].sort
    elements.each do |element|

      yield element, frequency
    end
  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



286
287
288
289
290
291
292
# File 'lib/xqsr3/containers/frequency_map.rb', line 286

def each_by_key

  @elements.keys.sort.each do |key|

    yield key, @elements[key]
  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



322
323
324
325
326
327
328
329
330
# File 'lib/xqsr3/containers/frequency_map.rb', line 322

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



336
337
338
339
340
341
342
343
344
# File 'lib/xqsr3/containers/frequency_map.rb', line 336

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)


347
348
349
350
# File 'lib/xqsr3/containers/frequency_map.rb', line 347

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)


354
355
356
357
358
359
360
361
362
# File 'lib/xqsr3/containers/frequency_map.rb', line 354

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



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
395
396
397
398
# File 'lib/xqsr3/containers/frequency_map.rb', line 369

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



401
402
403
404
# File 'lib/xqsr3/containers/frequency_map.rb', line 401

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)


408
409
410
411
# File 'lib/xqsr3/containers/frequency_map.rb', line 408

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)


421
422
423
424
425
426
427
428
429
430
431
# File 'lib/xqsr3/containers/frequency_map.rb', line 421

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



434
435
436
437
# File 'lib/xqsr3/containers/frequency_map.rb', line 434

def hash

  @elements.hash
end

#inspectObject

A diagnostics string form of the instance



442
443
444
445
# File 'lib/xqsr3/containers/frequency_map.rb', line 442

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)


461
462
463
464
465
466
# File 'lib/xqsr3/containers/frequency_map.rb', line 461

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



471
472
473
474
# File 'lib/xqsr3/containers/frequency_map.rb', line 471

def keys

  @elements.keys
end

#lengthObject Also known as: size

The number of elements in the map



477
478
479
480
# File 'lib/xqsr3/containers/frequency_map.rb', line 477

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)


489
490
491
492
493
494
495
496
497
498
499
# File 'lib/xqsr3/containers/frequency_map.rb', line 489

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



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/xqsr3/containers/frequency_map.rb', line 505

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)


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/xqsr3/containers/frequency_map.rb', line 535

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



558
559
560
561
562
563
564
565
# File 'lib/xqsr3/containers/frequency_map.rb', line 558

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)


576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/xqsr3/containers/frequency_map.rb', line 576

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



590
591
592
593
# File 'lib/xqsr3/containers/frequency_map.rb', line 590

def to_a

  @elements.to_a
end

#to_hObject

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



596
597
598
599
# File 'lib/xqsr3/containers/frequency_map.rb', line 596

def to_h

  @elements.to_h
end

#to_hashObject

Obtains equivalent hash to instance



602
603
604
605
# File 'lib/xqsr3/containers/frequency_map.rb', line 602

def to_hash

  @elements.to_hash
end

#to_sObject

A string-form of the instance



608
609
610
611
# File 'lib/xqsr3/containers/frequency_map.rb', line 608

def to_s

  @elements.to_s
end

#valuesObject

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



614
615
616
617
# File 'lib/xqsr3/containers/frequency_map.rb', line 614

def values

  @elements.values
end