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



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

def initialize

  @elements = {}
  @count    = 0
end

Class Method Details

.[](*args) ⇒ Object

Creates an instance from the given arguments



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

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

Signature

  • Parameters:

    • key The element to insert;



172
173
174
175
# File 'lib/xqsr3/containers/frequency_map.rb', line 172

def << key

  push key, 1
end

#==(rhs) ⇒ Object

Compares the instance for equality against rhs

Signature

  • Parameters:

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

Exceptions

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



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/xqsr3/containers/frequency_map.rb', line 186

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

Signature

  • Parameters:

    • key The key to lookup



212
213
214
215
# File 'lib/xqsr3/containers/frequency_map.rb', line 212

def [] key

  @elements[key] || 0
end

#[]=(key, count) ⇒ Object

Assigns a key and a count

Signature

  • Parameters:

    • key The key to lookup;

    • count (Integer) The count to lookup;

Exceptions

  • TypeError if count is not an Integer

Raises:

  • (TypeError)


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

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



236
237
238
239
# File 'lib/xqsr3/containers/frequency_map.rb', line 236

def assoc key

  @elements.assoc key
end

#clearObject

Removes all elements from the instance



242
243
244
245
246
# File 'lib/xqsr3/containers/frequency_map.rb', line 242

def clear

  @elements.clear
  @count = 0
end

#countObject

The total number of instances recorded



249
250
251
252
# File 'lib/xqsr3/containers/frequency_map.rb', line 249

def count

  @count
end

#defaultObject

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



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

def default

  @elements.default
end

#delete(key) ⇒ Object

Deletes the element with the given key and its counts

Signature

  • Parameters:

    • key The key to delete



266
267
268
269
270
271
# File 'lib/xqsr3/containers/frequency_map.rb', line 266

def delete key

  key_count = @elements.delete key

  @count -= key_count if key_count
end

#dupObject

Duplicates the instance



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

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



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

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



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

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



298
299
300
301
302
303
304
305
306
307
308
# File 'lib/xqsr3/containers/frequency_map.rb', line 298

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



329
330
331
332
333
334
335
336
337
# File 'lib/xqsr3/containers/frequency_map.rb', line 329

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



343
344
345
346
347
348
349
350
351
# File 'lib/xqsr3/containers/frequency_map.rb', line 343

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)


354
355
356
357
# File 'lib/xqsr3/containers/frequency_map.rb', line 354

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)


361
362
363
364
365
366
367
368
369
370
371
# File 'lib/xqsr3/containers/frequency_map.rb', line 361

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



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/xqsr3/containers/frequency_map.rb', line 378

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



415
416
417
418
# File 'lib/xqsr3/containers/frequency_map.rb', line 415

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)


422
423
424
425
# File 'lib/xqsr3/containers/frequency_map.rb', line 422

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

Signature

  • Parameters:

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

Exceptions

  • TypeError if value is not an Integer;

Returns:

  • (Boolean)


437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/xqsr3/containers/frequency_map.rb', line 437

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



452
453
454
455
# File 'lib/xqsr3/containers/frequency_map.rb', line 452

def hash

  @elements.hash
end

#inspectObject

A diagnostics string form of the instance



460
461
462
463
# File 'lib/xqsr3/containers/frequency_map.rb', line 460

def inspect

  make_inspect show_fields: true
end

#key(count) ⇒ Object

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

Signature

  • Parameters:

    • count (Integer) The count to lookup;

Exceptions

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

Raises:

  • (TypeError)


481
482
483
484
485
486
# File 'lib/xqsr3/containers/frequency_map.rb', line 481

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



491
492
493
494
# File 'lib/xqsr3/containers/frequency_map.rb', line 491

def keys

  @elements.keys
end

#lengthObject Also known as: size

The number of elements in the map



497
498
499
500
# File 'lib/xqsr3/containers/frequency_map.rb', line 497

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)


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

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



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/xqsr3/containers/frequency_map.rb', line 525

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)


555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/xqsr3/containers/frequency_map.rb', line 555

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



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

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)


596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/xqsr3/containers/frequency_map.rb', line 596

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



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

def to_a

  @elements.to_a
end

#to_hObject

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



616
617
618
619
# File 'lib/xqsr3/containers/frequency_map.rb', line 616

def to_h

  @elements.to_h
end

#to_hashObject

Obtains equivalent hash to instance



622
623
624
625
# File 'lib/xqsr3/containers/frequency_map.rb', line 622

def to_hash

  @elements.to_hash
end

#to_sObject

A string-form of the instance



628
629
630
631
# File 'lib/xqsr3/containers/frequency_map.rb', line 628

def to_s

  @elements.to_s
end

#valuesObject

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



634
635
636
637
# File 'lib/xqsr3/containers/frequency_map.rb', line 634

def values

  @elements.values
end