Class: Xqsr3::Containers::FrequencyMap
- Inherits:
-
Object
- Object
- Xqsr3::Containers::FrequencyMap
- 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
-
.[](*args) ⇒ Object
Creates an instance from the given arguments.
Instance Method Summary collapse
-
#<<(key) ⇒ Object
Pushes an element into the map, assigning it an initial count of 1.
-
#==(rhs) ⇒ Object
Compares the instance for equality against
rhs
. -
#[](key) ⇒ Object
Obtains the count for a given key, or
nil
if the key does not exist. -
#[]=(key, count) ⇒ Object
Assigns a key and a count.
-
#assoc(key) ⇒ Object
Searches the instance comparing each element with
key
, returning the count if found, ornil
if not. -
#clear ⇒ Object
Removes all elements from the instance.
-
#count ⇒ Object
The total number of instances recorded.
-
#default ⇒ Object
Obtains the default value of the instance, which will always be
nil
. -
#delete(key) ⇒ Object
Deletes the element with the given
key
and its counts. -
#dup ⇒ Object
Duplicates the instance.
-
#each ⇒ Object
(also: #each_pair)
Calls block once for each element in the instance, passing the element and its frequency as parameters.
-
#each_by_frequency ⇒ Object
Enumerates each entry pair - element + frequency - in descending order of frequency.
-
#each_by_key ⇒ Object
Enumerates each entry pair - element + frequency - in key order.
-
#each_key ⇒ Object
Calls block once for each element in the instance, passing the element.
-
#each_value ⇒ Object
Calls block once for each element in the instance, passing the count.
-
#empty? ⇒ Boolean
Returns
true
if instance contains no elements;false
otherwise. -
#eql?(rhs) ⇒ Boolean
Returns
true
ifrhs
is an instance ofFrequencyMap
and contains the same elements and their counts;false
otherwise. -
#fetch(key, default = nil, &block) ⇒ Object
Returns the count from the instance for the given element
key
. -
#flatten ⇒ Object
Returns the equivalent flattened form of the instance.
-
#has_key?(key) ⇒ Boolean
(also: #include?, #key?, #member?)
Returns
true
if an element with the givenkey
is in the map;false
otherwise. -
#has_value?(value) ⇒ Boolean
Returns
true
if an element with a count of the givenvalue
is in the map;false
otherwise. -
#hash ⇒ Object
A hash-code for this instance.
-
#initialize ⇒ FrequencyMap
constructor
Initialises an instance.
-
#inspect ⇒ Object
A diagnostics string form of the instance.
-
#key(count) ⇒ Object
Returns the element that has the given count, or
nil
if none found. -
#keys ⇒ Object
An array of the elements only.
-
#length ⇒ Object
(also: #size)
The number of elements in the map.
-
#merge(fm) ⇒ Object
Returns a new instance containing a merging of the current instance and the
fm
instance. -
#merge!(fm) ⇒ Object
Merges the contents of
fm
into the current instance. -
#push(key, count = 1) ⇒ Object
Pushes the
element
andcount
. -
#shift ⇒ Object
Removes a key-value pair from the instance and return as a two-item array.
-
#store(key, count) ⇒ Object
Causes an element with the given
key
andcount
to be stored. -
#to_a ⇒ Object
Converts instance to an array of [key,value] pairs.
-
#to_h ⇒ Object
Obtains reference to internal hash instance (which must not be modified).
-
#to_hash ⇒ Object
Obtains equivalent hash to instance.
-
#to_s ⇒ Object
A string-form of the instance.
-
#values ⇒ Object
An array of all frequencies (without element keys) in the instance.
Methods included from Diagnostics::InspectBuilder
Methods included from Enumerable
#collect_with_index, #detect_map, #unique
Constructor Details
#initialize ⇒ FrequencyMap
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
ifrhs
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
ifcount
is not anInteger
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 |
#clear ⇒ Object
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 |
#count ⇒ Object
The total number of instances recorded
249 250 251 252 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 249 def count @count end |
#default ⇒ Object
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 |
#dup ⇒ Object
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 |
#each ⇒ Object 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_frequency ⇒ Object
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_key ⇒ Object
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_key ⇒ Object
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_value ⇒ Object
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
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
361 362 363 364 365 366 367 368 369 |
# 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
376 377 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 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 376 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 |
#flatten ⇒ Object
Returns the equivalent flattened form of the instance
408 409 410 411 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 408 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
415 416 417 418 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 415 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
ifvalue
is not an Integer;
430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 430 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 |
#hash ⇒ Object
A hash-code for this instance
443 444 445 446 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 443 def hash @elements.hash end |
#inspect ⇒ Object
A diagnostics string form of the instance
451 452 453 454 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 451 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
ifcount
is not of the required type(s);
472 473 474 475 476 477 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 472 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 |
#keys ⇒ Object
An array of the elements only
482 483 484 485 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 482 def keys @elements.keys end |
#length ⇒ Object Also known as: size
The number of elements in the map
488 489 490 491 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 488 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
500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 500 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
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 516 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 ofcount
results in a negative count for the given element; -
TypeError
ifcount
is not anInteger
;
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 546 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 |
#shift ⇒ Object
Removes a key-value pair from the instance and return as a two-item array
569 570 571 572 573 574 575 576 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 569 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
587 588 589 590 591 592 593 594 595 596 597 598 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 587 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_a ⇒ Object
Converts instance to an array of [key,value] pairs
601 602 603 604 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 601 def to_a @elements.to_a end |
#to_h ⇒ Object
Obtains reference to internal hash instance (which must not be modified)
607 608 609 610 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 607 def to_h @elements.to_h end |
#to_hash ⇒ Object
Obtains equivalent hash to instance
613 614 615 616 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 613 def to_hash @elements.to_hash end |
#to_s ⇒ Object
A string-form of the instance
619 620 621 622 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 619 def to_s @elements.to_s end |
#values ⇒ Object
An array of all frequencies (without element keys) in the instance
625 626 627 628 |
# File 'lib/xqsr3/containers/frequency_map.rb', line 625 def values @elements.values end |