Class: Hamster::Vector

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hamster/vector.rb

Overview

A Vector is an ordered, integer-indexed collection of objects. Like Array, Vector indexing starts at 0. Also like Array, negative indexes count back from the end of the Vector.

Vector's interface is modeled after that of Array, minus all the methods which do destructive updates. Some methods which modify Arrays destructively (like #insert or #delete_at) are included, but they return new Vectors and leave the existing one unchanged.

Creating New Vectors

Hamster.vector('a', 'b', 'c')
Hamster::Vector.new([:first, :second, :third])
Hamster::Vector[1, 2, 3, 4, 5]

Retrieving Items from Vectors

require 'hamster/vector'
vector = Hamster.vector(1, 2, 3, 4, 5)
vector[0]      # => 1
vector[-1]     # => 5
vector[0,3]    # => Hamster::Vector[1, 2, 3]
vector[1..-1]  # => Hamster::Vector[2, 3, 4, 5]
vector.first   # => 1
vector.last    # => 5

Creating Modified Vectors

vector.add(6)            # => Hamster::Vector[1, 2, 3, 4, 5, 6]
vector.insert(1, :a, :b) # => Hamster::Vector[1, :a, :b, 2, 3, 4, 5]
vector.delete_at(2)      # => Hamster::Vector[1, 2, 4, 5]
vector + [6, 7]          # => Hamster::Vector[1, 2, 3, 4, 5, 6, 7]

Other Array-like methods like #select, #map, #shuffle, #uniq, #reverse, #rotate, #flatten, #sort, #sort_by, #take, #drop, #take_while, #drop_while, #fill, #product, and #transpose are also supported.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#<=>, #==, #compact, #each_index, #grep, #group_by, #inspect, #join, #partition, #reject, #sum, #to_set

Methods included from Enumerable

#to_list

Constructor Details

#initialize(items = [].freeze) ⇒ Vector

Returns a new instance of Vector


95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/hamster/vector.rb', line 95

def initialize(items=[].freeze)
  items = items.to_a
  if items.size <= 32
    items = items.dup.freeze if !items.frozen?
    @root, @size, @levels = items, items.size, 0
  else
    root, size, levels = items, items.size, 0
    while root.size > 32
      root = root.each_slice(32).to_a
      levels += 1
    end
    @root, @size, @levels = root.freeze, size, levels
  end
end

Instance Attribute Details

#sizeInteger (readonly) Also known as: length

Return the number of items in this Vector

Returns:

  • (Integer)

63
64
65
# File 'lib/hamster/vector.rb', line 63

def size
  @size
end

Class Method Details

.[](*items) ⇒ Vector

Create a new Vector populated with the given items.

Returns:


69
70
71
# File 'lib/hamster/vector.rb', line 69

def [](*items)
  new(items.freeze)
end

.emptyVector

Return an empty Vector. If used on a subclass, returns an empty instance of that class.

Returns:


77
78
79
# File 'lib/hamster/vector.rb', line 77

def empty
  @empty ||= self.new
end

Instance Method Details

#*(times) ⇒ Vector

Repetition. Return a new Vector built by concatenating times copies of this one together.

Examples:

Hamster::Vector["A", "B"] * 3
# => Hamster::Vector["A", "B", "A", "B", "A", "B"]

Parameters:

  • times (Integer)

    The number of times to repeat the elements in this vector

Returns:


687
688
689
690
691
692
# File 'lib/hamster/vector.rb', line 687

def *(times)
  return self.class.empty if times == 0
  return self if times == 1
  result = (to_a * times)
  result.is_a?(Array) ? self.class.new(result) : result
end

#+(other) ⇒ Vector Also known as: concat

Return a new Vector built by concatenating this one with other. other can be any object which is convertible to an Array using #to_a.

Examples:

Hamster::Vector["A", "B", "C"] + ["D", "E"]
# => Hamster::Vector["A", "B", "C", "D", "E"]

Parameters:

  • other (Enumerable)

    The collection to concatenate onto this vector

Returns:


562
563
564
565
566
# File 'lib/hamster/vector.rb', line 562

def +(other)
  other = other.to_a
  other = other.dup if other.frozen?
  replace_suffix(@size, other)
end

#vectorObject #vectorObject #vectorObject Also known as: slice

Element reference. Return the item at a specific index, or a specified, contiguous range of items (as a new Vector).

Examples:

v = Hamster::Vector["A", "B", "C", "D", "E", "F"]
v[2]     # => "C"
v[-1]    # => "D"
v[6]     # => nil
v[2, 2]  # => Hamster::Vector["C", "D"]
v[2..3]  # => Hamster::Vector["C", "D"]

Overloads:

  • #vectorObject

    Return the item at index.

    Parameters:

    • index (Integer)

      The index to retrieve.

  • #vectorObject

    Return a subvector starting at index start and continuing for length elements.

    Parameters:

    • start (Integer)

      The index to start retrieving items from.

    • length (Integer)

      The number of items to retrieve.

  • #vectorObject

    Return a subvector specified by the given range of indices.

    Parameters:

    • range (Range)

      The range of indices to retrieve.

Returns:

  • (Object)

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/hamster/vector.rb', line 296

def [](arg, length = (missing_length = true))
  if missing_length
    if arg.is_a?(Range)
      from, to = arg.begin, arg.end
      from += @size if from < 0
      to   += @size if to < 0
      to   += 1     if !arg.exclude_end?
      length = to - from
      length = 0 if length < 0
      subsequence(from, length)
    else
      get(arg)
    end
  else
    arg += @size if arg < 0
    subsequence(arg, length)
  end
end

#add(item) ⇒ Vector Also known as: <<, push

Return a new Vector with item added after the last occupied position.

Examples:

Hamster::Vector[1, 2].add(99)  # => Hamster::Vector[1, 2, 99]

Parameters:

  • item (Object)

    The object to insert at the end of the vector

Returns:


144
145
146
# File 'lib/hamster/vector.rb', line 144

def add(item)
  update_root(@size, item)
end

#assoc(obj) ⇒ Object

Assumes all elements are nested, indexable collections, and searches through them, comparing obj with the first element of each nested collection. Return the first nested collection which matches, or nil if none is found.

Examples:

v = Hamster::Vector[["A", 10], ["B", 20], ["C", 30]]
v.assoc("B")  # => ["B", 20]

Parameters:

  • obj (Object)

    The object to search for

Returns:

  • (Object)

1143
1144
1145
1146
# File 'lib/hamster/vector.rb', line 1143

def assoc(obj)
  each { |array| return array if obj == array[0] }
  nil
end

#bsearchObject

By using binary search, finds a value from this Vector which meets the condition defined by the provided block. Behavior is just like Array#bsearch. See Array#bsearch for details.

Examples:

v = Hamster::Vector[1, 3, 5, 7, 9, 11, 13]
# Block returns true/false for exact element match:
v.bsearch { |e| e > 4 }      # => 5
# Block returns number to match an element in 4 <= e <= 7:
v.bsearch { |e| 1 - e / 4 }  # => 7

Returns:

  • (Object)

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
# File 'lib/hamster/vector.rb', line 1044

def bsearch
  low, high, result = 0, @size, nil
  while low < high
    mid = (low + ((high - low) >> 1))
    val = get(mid)
    v   = yield val
    if v.is_a? Numeric
      if v == 0
        return val
      elsif v > 0
        high = mid
      else
        low = mid + 1
      end
    elsif v == true
      result = val
      high = mid
    elsif !v
      low = mid + 1
    else
      raise TypeError, "wrong argument type #{v.class} (must be numeric, true, false, or nil)"
    end
  end
  result
end

#clearVector

Return an empty Vector instance, of the same class as this one. Useful if you have multiple subclasses of Vector and want to treat them polymorphically.

Returns:


1074
1075
1076
# File 'lib/hamster/vector.rb', line 1074

def clear
  self.class.empty
end

#combination(n) ⇒ self, Enumerator

When invoked with a block, yields all combinations of length n of items from the Vector, and then returns self. There is no guarantee about which order the combinations will be yielded in.

If no block is given, an Enumerator is returned instead.

Examples:

v = Hamster::Vector[5, 6, 7, 8]
v.combination(3) { |c| puts "Combination: #{c}" }

Combination: [5, 6, 7]
Combination: [5, 6, 8]
Combination: [5, 7, 8]
Combination: [6, 7, 8]
#=> Hamster::Vector[5, 6, 7, 8]

Returns:

  • (self, Enumerator)

750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/hamster/vector.rb', line 750

def combination(n)
  return enum_for(:combination, n) if not block_given?
  return self if n < 0 || @size < n
  if n == 0
    yield []
  elsif n == 1
    each { |item| yield [item] }
  elsif n == @size
    yield self.to_a
  else
    combos = lambda do |result,index,remaining|
      while @size - index > remaining
        if remaining == 1
          yield result.dup << get(index)
        else
          combos[result.dup << get(index), index+1, remaining-1]
        end
        index += 1
      end
      index.upto(@size-1) { |i| result << get(i) }
      yield result
    end
    combos[[], 0, n]
  end
  self
end

#delete(obj) ⇒ Vector

Return a new Vector with all items which are equal to obj removed. #== is used for checking equality.

Examples:

Hamster::Vector["C", "B", "A", "B"].delete("B")  # => Hamster::Vector["C", "A"]

Parameters:

  • obj (Object)

    The object to remove (every occurrence)

Returns:


451
452
453
# File 'lib/hamster/vector.rb', line 451

def delete(obj)
  select { |item| item != obj }
end

#delete_at(index) ⇒ Vector

Return a new Vector with the element at index removed. If the given index does not exist, return self.

Examples:

Hamster::Vector["A", "B", "C", "D"].delete_at(2)
# => Hamster::Vector["A", "B", "D"]

Parameters:

  • index (Integer)

    The index to remove

Returns:


351
352
353
354
355
356
357
# File 'lib/hamster/vector.rb', line 351

def delete_at(index)
  return self if index >= @size || index < -@size
  index += @size if index < 0

  suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
  replace_suffix(index, suffix.tap { |a| a.shift })
end

#drop(n) ⇒ Vector

Drop the first n elements and return the rest in a new Vector.

Examples:

Hamster::Vector["A", "B", "C", "D", "E", "F"].drop(2)
# => Hamster::Vector["C", "D", "E", "F"]

Parameters:

  • n (Integer)

    The number of elements to remove

Returns:

Raises:

  • (ArgumentError)

630
631
632
633
634
635
# File 'lib/hamster/vector.rb', line 630

def drop(n)
  return self if n == 0
  return self.class.empty if n >= @size
  raise ArgumentError, "attempt to drop negative size" if n < 0
  self.class.new(flatten_suffix(@root, @levels * BITS_PER_LEVEL, n, []))
end

#drop_whileVector, Enumerator

Drop elements up to, but not including, the first element for which the block returns nil or false. Gather the remaining elements into a new Vector. If no block is given, an Enumerator is returned instead.

Examples:

Hamster::Vector[1, 3, 5, 7, 6, 4, 2].drop_while { |e| e < 5 }
# => Hamster::Vector[5, 7, 6, 4, 2]

Returns:


659
660
661
662
# File 'lib/hamster/vector.rb', line 659

def drop_while
  return enum_for(:drop_while) if not block_given?
  self.class.new(super)
end

#each(&block) ⇒ self

Call the given block once for each item in the vector, passing each item from first to last successively to the block.

Examples:

Hamster::Vector["A", "B", "C"].each { |e| puts "Element: #{e}" }

Element: A
Element: B
Element: C
# => Hamster::Vector["A", "B", "C"]

Returns:

  • (self)

404
405
406
407
408
# File 'lib/hamster/vector.rb', line 404

def each(&block)
  return to_enum unless block_given?
  traverse_depth_first(@root, @levels, &block)
  self
end

#empty?Boolean

Return true if this Vector contains no items.

Returns:

  • (Boolean)

113
114
115
# File 'lib/hamster/vector.rb', line 113

def empty?
  @size == 0
end

#eql?(other) ⇒ Boolean

Return true if other has the same type and contents as this Vector.

Parameters:

  • other (Object)

    The collection to compare with

Returns:

  • (Boolean)

1187
1188
1189
1190
1191
# File 'lib/hamster/vector.rb', line 1187

def eql?(other)
  return true if other.equal?(self)
  return false unless instance_of?(other.class) && @size == other.size
  @root.eql?(other.instance_variable_get(:@root))
end

#fetch(index) ⇒ Object #fetch(index) {|index| ... } ⇒ Object #fetch(index, default) ⇒ Object

Retrieve the value at index, or use the provided default value or block, or otherwise raise an IndexError.

Examples:

v = Hamster::Vector["A", "B", "C", "D"]
v.fetch(2)       # => "C"
v.fetch(-1)      # => "D"
v.fetch(4)       # => IndexError: index 4 outside of vector bounds
# With default value:
v.fetch(2, "Z")  # => "C"
v.fetch(4, "Z")  # => "Z"
# With block:
v.fetch(2) { |i| i * i }   # => "C"
v.fetch(4) { |i| i * i }   # => 16

Overloads:

  • #fetch(index) ⇒ Object

    Retrieve the value at the given index, or raise an IndexError if it is not found.

    Parameters:

    • index (Integer)

      The index to look up

  • #fetch(index) {|index| ... } ⇒ Object

    Retrieve the value at the given index, or call the optional code block (with the non-existent index) and get its return value.

    Parameters:

    • index (Integer)

      The index to look up

    Yields:

    • (index)

      The index which does not exist

    Yield Returns:

    • (Object)

      Object to return instead

  • #fetch(index, default) ⇒ Object

    Retrieve the value at the given index, or else return the provided default value.

    Parameters:

    • index (Integer)

      The index to look up

    • default (Object)

      Object to return if the key is not found

Returns:

  • (Object)

261
262
263
264
265
266
267
268
269
270
271
# File 'lib/hamster/vector.rb', line 261

def fetch(index, default = (missing_default = true))
  if index >= -@size && index < @size
    get(index)
  elsif block_given?
    yield(index)
  elsif !missing_default
    default
  else
    raise IndexError, "index #{index} outside of vector bounds"
  end
end

#fill(obj) ⇒ Vector #fill(obj, start) ⇒ Vector #fill(obj, start, length) ⇒ Vector

Replace a range of indexes with the given object.

Examples:

v = Hamster::Vector["A", "B", "C", "D", "E", "F"]
v.fill("Z")
# => Hamster::Vector["Z", "Z", "Z", "Z", "Z", "Z"]
v.fill("Z", 3)
# => Hamster::Vector["A", "B", "C", "Z", "Z", "Z"]
v.fill("Z", 3, 2)
# => Hamster::Vector["A", "B", "C", "Z", "Z", "F"]

Overloads:

  • #fill(obj) ⇒ Vector

    Return a new Vector of the same size, with every index set to obj.

  • #fill(obj, start) ⇒ Vector

    Return a new Vector with all indexes from start to the end of the vector set to obj.

  • #fill(obj, start, length) ⇒ Vector

    Return a new Vector with length indexes, beginning from start, set to obj.

Returns:

Raises:

  • (IndexError)

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/hamster/vector.rb', line 715

def fill(obj, index = 0, length = nil)
  raise IndexError if index < -@size
  index += @size if index < 0
  length ||= @size - index # to the end of the array, if no length given

  if index < @size
    suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
    suffix.fill(obj, 0, length)
  elsif index == @size
    suffix = Array.new(length, obj)
  else
    suffix = Array.new(index - @size, nil).concat(Array.new(length, obj))
    index = @size
  end

  replace_suffix(index, suffix)
end

#firstObject

Return the first item in the Vector. If the vector is empty, return nil.

Examples:

Hamster::Vector["A", "B", "C"].first  # => "A"

Returns:

  • (Object)

123
124
125
# File 'lib/hamster/vector.rb', line 123

def first
  get(0)
end

#flat_mapVector

Return a new Vector with the concatenated results of running the block once for every element in this Vector.

Examples:

Hamster.vector(1, 2, 3).flat_map { |x| [x, -x] }
# => Hamster::Vector[1, -1, 2, -2, 3, -3]

Returns:


477
478
479
480
481
# File 'lib/hamster/vector.rb', line 477

def flat_map
  return enum_for(:flat_map) if not block_given?
  return self if empty?
  self.class.new(super)
end

#flatten(level = -1)) ⇒ Vector

Return a new Vector with all nested vectors and arrays recursively "flattened out", that is, their elements inserted into the new Vector in the place where the nested array/vector originally was. If an optional level argument is provided, the flattening will only be done recursively that number of times. A level of 0 means not to flatten at all, 1 means to only flatten nested arrays/vectors which are directly contained within this Vector.

Examples:

v = Hamster::Vector["A", Hamster::Vector["B", "C", Hamster::Vector["D"]]]
v.flatten(1)
# => Hamster::Vector["A", "B", "C", Hamster::Vector["D"]]
v.flatten
# => Hamster::Vector["A", "B", "C", "D"]

Parameters:

  • level (Integer) (defaults to: -1))

    The depth to which flattening should be applied

Returns:


548
549
550
551
# File 'lib/hamster/vector.rb', line 548

def flatten(level = -1)
  return self if level == 0
  self.class.new(((array = to_a).frozen? ? array.flatten(level) : array.flatten!(level)).freeze)
end

#get(index) ⇒ Object Also known as: at

Retrieve the item at index. If there is none (either the provided index is too high or too low), return nil.

Examples:

v = Hamster::Vector["A", "B", "C", "D"]
v.get(2)   # => "C"
v.get(-1)  # => "D"
v.get(4)   # => nil

Parameters:

  • index (Integer)

    The index to retrieve

Returns:

  • (Object)

221
222
223
224
225
226
# File 'lib/hamster/vector.rb', line 221

def get(index)
  return nil if @size == 0
  index += @size if index < 0
  return nil if index >= @size || index < 0
  leaf_node_for(@root, @levels * BITS_PER_LEVEL, index)[index & INDEX_MASK]
end

#hashInteger

See Object#hash.

Returns:

  • (Integer)

1195
1196
1197
# File 'lib/hamster/vector.rb', line 1195

def hash
  reduce(0) { |hash, item| (hash << 5) - hash + item.hash }
end

#insert(index, *items) ⇒ Vector

Return a new Vector with the given values inserted before the element at index.

Examples:

Hamster::Vector["A", "B", "C", "D"].insert(2, "X", "Y", "Z")
# => Hamster::Vector["A", "B", "X", "Y", "Z", "C", "D"]

Parameters:

  • index (Integer)

    The index where the new items should go

  • items (Array)

    The items to add

Returns:

Raises:

  • (IndexError)

325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/hamster/vector.rb', line 325

def insert(index, *items)
  raise IndexError if index < -@size
  index += @size if index < 0

  if index < @size
    suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
    suffix.unshift(*items)
  elsif index == @size
    suffix = items
  else
    suffix = Array.new(index - @size, nil).concat(items)
    index = @size
  end

  replace_suffix(index, suffix)
end

#lastObject

Return the last item in the Vector. If the vector is empty, return nil.

Examples:

Hamster::Vector["A", "B", "C"].last  # => "C"

Returns:

  • (Object)

133
134
135
# File 'lib/hamster/vector.rb', line 133

def last
  get(-1)
end

#mapVector Also known as: collect

Invoke the given block once for each item in the vector, and return a new Vector containing the values returned by the block.

Examples:

Hamster::Vector[3, 2, 1].map { |e| e * e }  # => Hamster::Vector[9, 4, 1]

Returns:


462
463
464
465
466
# File 'lib/hamster/vector.rb', line 462

def map
  return enum_for(:map) if not block_given?
  return self if empty?
  self.class.new(super)
end

#permutation(n = @size) ⇒ self, Enumerator

Yields all permutations of length n of items from the Vector, and then returns self. If no length n is specified, permutations of all elements will be yielded.

There is no guarantee about which order the permutations will be yielded in.

If no block is given, an Enumerator is returned instead.

Examples:

v = Hamster::Vector[5, 6, 7]
v.permutation(2) { |p| puts "Permutation: #{p}" }

Permutation: [5, 6]
Permutation: [5, 7]
Permutation: [6, 5]
Permutation: [6, 7]
Permutation: [7, 5]
Permutation: [7, 6]
# => Hamster::Vector[5, 6, 7]

Returns:

  • (self, Enumerator)

853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/hamster/vector.rb', line 853

def permutation(n = @size)
  return enum_for(:permutation, n) if not block_given?
  if n < 0 || @size < n
    # yield nothing
  elsif n == 0
    yield []
  elsif n == 1
    each { |item| yield [item] }
  else
    used, result = [], []
    perms = lambda do |index|
      0.upto(@size-1) do |i|
        if !used[i]
          result[index] = get(i)
          if index < n-1
            used[i] = true
            perms[index+1]
            used[i] = false
          else
            yield result.dup
          end
        end
      end
    end
    perms[0]
  end
  self
end

#popVector

Return a new Vector with the last element removed. If empty, just return self.

Examples:

Hamster::Vector["A", "B", "C"].pop  # => Hamster::Vector["A", "B"]

Returns:


365
366
367
368
# File 'lib/hamster/vector.rb', line 365

def pop
  return self if @size == 0
  replace_suffix(@size-1, [])
end

#product(*vectors) ⇒ Vector #productVector

With one or more vector or array arguments, return the cartesian product of this vector's elements and those of each argument; with no arguments, return the result of multiplying all this vector's items together.

Examples:

# Cartesian product:
v1 = Hamster::Vector[1, 2, 3]
v2 = Hamster::Vector["A", "B"]
v1.product(v2)
# => [[1, "A"], [1, "B"], [2, "A"], [2, "B"], [3, "A"], [3, "B"]]

# Multiply all items:
Hamster::Vector[1, 2, 3, 4, 5].product  # => 120

Overloads:

  • #product(*vectors) ⇒ Vector

    Return a Vector of all combinations of elements from this Vector and each of the given vectors or arrays. The length of the returned Vector is the product of self.size and the size of each argument vector or array.

  • #productVector

    Return the result of multiplying all the items in this Vector together.

Returns:


955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
# File 'lib/hamster/vector.rb', line 955

def product(*vectors)
  # if no vectors passed, return "product" as in result of multiplying all items
  return super if vectors.empty?

  vectors.unshift(self)

  if vectors.any?(&:empty?)
    return block_given? ? self : []
  end

  counters = Array.new(vectors.size, 0)

  bump_counters = lambda do
    i = vectors.size-1
    counters[i] += 1
    while counters[i] == vectors[i].size
      counters[i] = 0
      i -= 1
      return true if i == -1 # we are done
      counters[i] += 1
    end
    false # not done yet
  end
  build_array = lambda do
    array = []
    counters.each_with_index { |index,i| array << vectors[i][index] }
    array
  end

  if block_given?
    while true
      yield build_array[]
      return self if bump_counters[]
    end
  else
    result = []
    while true
      result << build_array[]
      return result if bump_counters[]
    end
  end
end

#rassoc(obj) ⇒ Object

Assumes all elements are nested, indexable collections, and searches through them, comparing obj with the second element of each nested collection. Return the first nested collection which matches, or nil if none is found.

Examples:

v = Hamster::Vector[["A", 10], ["B", 20], ["C", 30]]
v.rassoc(20)  # => ["B", 20]

Parameters:

  • obj (Object)

    The object to search for

Returns:

  • (Object)

1158
1159
1160
1161
# File 'lib/hamster/vector.rb', line 1158

def rassoc(obj)
  each { |array| return array if obj == array[1] }
  nil
end

#repeated_combination(n) ⇒ self, Enumerator

When invoked with a block, yields all repeated combinations of length n of items from the Vector, and then returns self. A "repeated combination" is one in which any item from the Vector can appear consecutively any number of times.

There is no guarantee about which order the combinations will be yielded in.

If no block is given, an Enumerator is returned instead.

Examples:

v = Hamster::Vector[5, 6, 7, 8]
v.repeated_combination(2) { |c| puts "Combination: #{c}" }

Combination: [5, 5]
Combination: [5, 6]
Combination: [5, 7]
Combination: [5, 8]
Combination: [6, 6]
Combination: [6, 7]
Combination: [6, 8]
Combination: [7, 7]
Combination: [7, 8]
Combination: [8, 8]
# => Hamster::Vector[5, 6, 7, 8]

Returns:

  • (self, Enumerator)

803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/hamster/vector.rb', line 803

def repeated_combination(n)
  return enum_for(:repeated_combination, n) if not block_given?
  if n < 0
    # yield nothing
  elsif n == 0
    yield []
  elsif n == 1
    each { |item| yield [item] }
  elsif @size == 0
    # yield nothing
  else
    combos = lambda do |result,index,remaining|
      while index < @size-1
        if remaining == 1
          yield result.dup << get(index)
        else
          combos[result.dup << get(index), index, remaining-1]
        end
        index += 1
      end
      item = get(index)
      remaining.times { result << item }
      yield result
    end
    combos[[], 0, n]
  end
  self
end

#repeated_permutation(n = @size) ⇒ self, Enumerator

When invoked with a block, yields all repeated permutations of length n of items from the Vector, and then returns self. A "repeated permutation" is one where any item from the Vector can appear any number of times, and in any position (not just consecutively)

If no length n is specified, permutations of all elements will be yielded. There is no guarantee about which order the permutations will be yielded in.

If no block is given, an Enumerator is returned instead.

Examples:

v = Hamster::Vector[5, 6, 7]
v.repeated_permutation(2) { |p| puts "Permutation: #{p}" }

Permutation: [5, 5]
Permutation: [5, 6]
Permutation: [5, 7]
Permutation: [6, 5]
Permutation: [6, 6]
Permutation: [6, 7]
Permutation: [7, 5]
Permutation: [7, 6]
Permutation: [7, 7]
# => Hamster::Vector[5, 6, 7]

Returns:

  • (self, Enumerator)

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/hamster/vector.rb', line 908

def repeated_permutation(n = @size)
  return enum_for(:repeated_permutation, n) if not block_given?
  if n < 0
    # yield nothing
  elsif n == 0
    yield []
  elsif n == 1
    each { |item| yield [item] }
  else
    result = []
    perms = lambda do |index|
      0.upto(@size-1) do |i|
        result[index] = get(i)
        if index < n-1
          perms[index+1]
        else
          yield result.dup
        end
      end
    end
    perms[0]
  end
  self
end

#reverseVector

Return a new Vector with the same elements as this one, but in reverse order.

Examples:

Hamster::Vector["A", "B", "C"].reverse  # => Hamster::Vector["C", "B", "A"]

Returns:


510
511
512
# File 'lib/hamster/vector.rb', line 510

def reverse
  self.class.new(((array = to_a).frozen? ? array.reverse : array.reverse!).freeze)
end

#reverse_each(&block) ⇒ self

Call the given block once for each item in the vector, passing each item starting from the last, and counting back to the first, successively to the block.

Examples:

Hamster::Vector["A", "B", "C"].reverse_each { |e| puts "Element: #{e}" }

Element: C
Element: B
Element: A

Returns:

  • (self)

422
423
424
425
426
# File 'lib/hamster/vector.rb', line 422

def reverse_each(&block)
  return enum_for(:reverse_each) unless block_given?
  reverse_traverse_depth_first(@root, @levels, &block)
  self
end

#rindex(obj) ⇒ Index #rindex({ |item| ... }) ⇒ Index

Return the index of the last element which is equal to the provided object, or for which the provided block returns true.

Examples:

v = Hamster::Vector[7, 8, 9, 7, 8, 9]
v.rindex(8)               # => 4
v.rindex { |e| e.even? }  # => 4

Overloads:

  • #rindex(obj) ⇒ Index

    Return the index of the last element in this Vector which is #== to obj.

  • #rindex({ |item| ... }) ⇒ Index

    Return the index of the last element in this Vector for which the block returns true. (Iteration starts from the last element, counts back, and stops as soon as a matching element is found.)

Returns:

  • (Index)

1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
# File 'lib/hamster/vector.rb', line 1118

def rindex(obj = (missing_arg = true))
  i = @size - 1
  if missing_arg
    if block_given?
      reverse_each { |item| return i if yield item; i -= 1 }
      nil
    else
      enum_for(:rindex)
    end
  else
    reverse_each { |item| return i if item == obj; i -= 1 }
    nil
  end
end

#rotate(count = 1) ⇒ Vector

Return a new Vector with the same elements, but rotated so that the one at index count is the first element of the new vector. If count is positive, the elements will be shifted left, and those shifted past the lowest position will be moved to the end. If count is negative, the elements will be shifted right, and those shifted past the last position will be moved to the beginning.

Examples:

v = Hamster::Vector["A", "B", "C", "D", "E", "F"]
v.rotate(2)   # => Hamster::Vector["C", "D", "E", "F", "A", "B"]
v.rotate(-1)  # => Hamster::Vector["F", "A", "B", "C", "D", "E"]

Parameters:

  • count (Integer) (defaults to: 1)

    The number of positions to shift items by

Returns:


527
528
529
530
# File 'lib/hamster/vector.rb', line 527

def rotate(count = 1)
  return self if (count % @size) == 0
  self.class.new(((array = to_a).frozen? ? array.rotate(count) : array.rotate!(count)).freeze)
end

#sampleObject

Return a randomly chosen item from this Vector. If the vector is empty, return nil.

Examples:

Hamster::Vector[1, 2, 3, 4, 5].sample  # => 2

Returns:

  • (Object)

1084
1085
1086
# File 'lib/hamster/vector.rb', line 1084

def sample
  get(rand(@size))
end

#selectVector Also known as: find_all, keep_if

Return a new Vector containing all elements for which the given block returns true.

Examples:

Hamster::Vector["Bird", "Cow", "Elephant"].select { |e| e.size >= 4 }
# => Hamster::Vector["Bird", "Elephant"]

Returns:


436
437
438
439
# File 'lib/hamster/vector.rb', line 436

def select
  return enum_for(:select) unless block_given?
  reduce(self.class.empty) { |vector, item| yield(item) ? vector.add(item) : vector }
end

#set(index, item = yield(get(index))) ⇒ Vector

Return a new Vector with the item at index replaced by item. If the item argument is missing, but an optional code block is provided, it will be passed the existing item and what the block returns will replace it.

Examples:

Hamster::Vector[1, 2, 3, 4].set(2, 99)
# => Hamster::Vector[1, 2, 99, 4]
Hamster::Vector[1, 2, 3, 4].set(2) { |v| v * 10 }
# => Hamster::Vector[1, 2, 30, 4]

Parameters:

  • index (Integer)

    The index to update

  • item (Object) (defaults to: yield(get(index)))

    The object to insert into that position

Returns:

Raises:

  • (IndexError)

163
164
165
166
167
168
169
170
171
172
173
# File 'lib/hamster/vector.rb', line 163

def set(index, item = yield(get(index)))
  raise IndexError, "index #{index} outside of vector bounds" if index < -@size
  index += @size if index < 0
  if index > @size
    suffix = Array.new(index - @size, nil)
    suffix << item
    replace_suffix(@size, suffix)
  else
    update_root(index, item)
  end
end

#shiftVector

Return a new Vector with the first element removed. If empty, just return self.

Examples:

Hamster::Vector["A", "B", "C"].shift  # => Hamster::Vector["B", "C"]

Returns:


388
389
390
# File 'lib/hamster/vector.rb', line 388

def shift
  delete_at(0)
end

#shuffleVector

Return a new Vector with the same elements as this one, but randomly permuted.

Examples:

Hamster::Vector[1, 2, 3, 4].shuffle  # => Hamster::Vector[4, 1, 3, 2]

Returns:


489
490
491
# File 'lib/hamster/vector.rb', line 489

def shuffle
  self.class.new(((array = to_a).frozen? ? array.shuffle : array.shuffle!).freeze)
end

#sortVector

Return a new Vector with the same items, but sorted. The sort order will be determined by comparing items using #<=>, or if an optional code block is provided, by using it as a comparator. The block should accept 2 parameters, and should return 0, 1, or -1 if the first parameter is equal to, greater than, or less than the second parameter (respectively).

Examples:

Hamster::Vector["Elephant", "Dog", "Lion"].sort
# => Hamster::Vector["Dog", "Elephant", "Lion"]
Hamster::Vector["Elephant", "Dog", "Lion"].sort { |a,b| a.size <=> b.size }
# => Hamster::Vector["Dog", "Lion", "Elephant"]

Returns:


605
606
607
# File 'lib/hamster/vector.rb', line 605

def sort
  self.class.new(super)
end

#sort_byVector

Return a new Vector with the same items, but sorted. The sort order will be determined by mapping the items through the given block to obtain sort keys, and then sorting the keys according to their natural sort order.

Examples:

Hamster::Vector["Elephant", "Dog", "Lion"].sort_by { |e| e.size }
# => Hamster::Vector["Dog", "Lion", "Elephant"]

Returns:


618
619
620
# File 'lib/hamster/vector.rb', line 618

def sort_by
  self.class.new(super)
end

#take(n) ⇒ Vector

Return only the first n elements in a new Vector.

Examples:

Hamster::Vector["A", "B", "C", "D", "E", "F"].take(4)
# => Hamster::Vector["A", "B", "C", "D"]

Parameters:

  • n (Integer)

    The number of elements to retain

Returns:


645
646
647
648
# File 'lib/hamster/vector.rb', line 645

def take(n)
  return self if n >= @size
  self.class.new(super)
end

#take_whileVector, Enumerator

Gather elements up to, but not including, the first element for which the block returns nil or false, and return them in a new Vector. If no block is given, an Enumerator is returned instead.

Examples:

Hamster::Vector[1, 3, 5, 7, 6, 4, 2].take_while { |e| e < 5 }
# => Hamster::Vector[1, 3]

Returns:


673
674
675
676
# File 'lib/hamster/vector.rb', line 673

def take_while
  return enum_for(:take_while) if not block_given?
  self.class.new(super)
end

#to_aArray Also known as: to_ary

Return an Array with the same elements, in the same order. The returned Array may or may not be frozen.

Returns:

  • (Array)

1167
1168
1169
1170
1171
1172
1173
# File 'lib/hamster/vector.rb', line 1167

def to_a
  if @levels == 0
    @root
  else
    flatten_node(@root, @levels * BITS_PER_LEVEL, [])
  end
end

#to_ruby::Array

Deeply convert to Ruby Array.

Returns:

  • (::Array)

1179
1180
1181
# File 'lib/hamster/vector.rb', line 1179

def to_ruby
  Hamster.to_ruby(self)
end

#transposeVector

Assume all elements are vectors or arrays and transpose the rows and columns. In other words, take the first element of each nested vector/array and gather them together into a new Vector. Do likewise for the second, third, and so on down to the end of each nested vector/array. Gather all the resulting Vectors into a new Vector and return it.

This operation is closely related to #zip. The result is almost the same as calling #zip on the first nested vector/array with the others supplied as arguments.

Examples:

Hamster::Vector[["A", 10], ["B", 20], ["C", 30]].transpose
# => Hamster::Vector[Hamster::Vector["A", "B", "C"], Hamster::Vector[10, 20, 30]]

Returns:


1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'lib/hamster/vector.rb', line 1013

def transpose
  return self.class.empty if empty?
  result = Array.new(first.size) { [] }

  0.upto(@size-1) do |i|
    source = get(i)
    if source.size != result.size
      raise IndexError, "element size differs (#{source.size} should be #{result.size})"
    end

    0.upto(result.size-1) do |j|
      result[j].push(source[j])
    end
  end

  result.map! { |a| self.class.new(a) }
  self.class.new(result)
end

#uniqVector

Return a new Vector with no duplicate elements, as determined by #hash and #eql?. For each group of equivalent elements, only the first will be retained.

Examples:

Hamster::Vector["A", "B", "C", "B"].uniq  # => Hamster::Vector["A", "B", "C"]

Returns:


500
501
502
# File 'lib/hamster/vector.rb', line 500

def uniq
  self.class.new(((array = to_a).frozen? ? array.uniq : array.uniq!).freeze)
end

#unshift(obj) ⇒ Vector

Return a new Vector with obj inserted before the first element, moving the other elements upwards.

Examples:

Hamster::Vector["A", "B"].unshift("Z")  # => Hamster::Vector["Z", "A", "B"]

Parameters:

  • obj (Object)

    The value to prepend

Returns:


378
379
380
# File 'lib/hamster/vector.rb', line 378

def unshift(obj)
  insert(0, obj)
end

#update_in(*key_path) {|value| ... } ⇒ Hash

Return a new Vector with a deeply nested value modified to the result of the given code block. When traversing the nested Vectors and Hashes, non-existing keys are created with empty Hash values.

The code block receives the existing value of the deeply nested key (or nil if it doesn't exist). This is useful for "transforming" the value associated with a certain key.

Note that the original Vector and sub-Vectors and sub-Hashes are left unmodified; new data structure copies are created along the path wherever needed.

Examples:

v = Hamster::Vector[123, 456, 789, Hamster::Hash["a" => Hamster::Vector[5, 6, 7]]]
v.update_in(3, "a", 1) { |value| value + 9 }
# => Hamster::Vector[123, 456, 789, Hamster::Hash["a" => Hamster::Vector[5, 15, 7]]]

Parameters:

  • key_path (Object(s))

    List of keys which form the path to the key to be modified

Yields:

  • (value)

    The previously stored value

Yield Returns:

  • (Object)

    The new value to store

Returns:


196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/hamster/vector.rb', line 196

def update_in(*key_path, &block)
  if key_path.empty?
    raise ArgumentError, "must have at least one key in path"
  end
  key = key_path[0]
  if key_path.size == 1
    new_value = block.call(get(key))
  else
    value = fetch(key, EmptyHash)
    new_value = value.update_in(*key_path[1..-1], &block)
  end
  set(key, new_value)
end

#values_at(*indices) ⇒ Vector

Return a new Vector with only the elements at the given indices, in the order specified by indices. If any of the indices do not exist, nils will appear in their places.

Examples:

v = Hamster::Vector["A", "B", "C", "D", "E", "F"]
v.values_at(2, 4, 5)   # => Hamster::Vector["C", "E", "F"]

Parameters:

  • indices (Array)

    The indices to retrieve and gather into a new Vector

Returns:


1098
1099
1100
# File 'lib/hamster/vector.rb', line 1098

def values_at(*indices)
  self.class.new(indices.map { |i| get(i) }.freeze)
end

#zip(*others) ⇒ Vector?

others should be arrays and/or vectors. The corresponding elements from this Vector and each of others (that is, the elements with the same indices) will be gathered into arrays.

If an optional block is provided, each such array will be passed successively to the block. Otherwise, a new Vector of all those arrays will be returned.

Examples:

v1 = Hamster::Vector["A", "B", "C"]
v2 = Hamster::Vector[1, 2, 3]
v1.zip(v2)
# => Hamster::Vector[["A", 1], ["B", 2], ["C", 3]]

Parameters:

  • others (Array)

    The arrays/vectors to zip together with this one

Returns:


584
585
586
587
588
589
590
# File 'lib/hamster/vector.rb', line 584

def zip(*others)
  if block_given?
    super
  else
    self.class.new(super)
  end
end