Class: Warray

Inherits:
Object
  • Object
show all
Defined in:
lib/warray.rb,
lib/warray/version.rb

Overview

Warray

Constant Summary collapse

VERSION =
"0.0.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(a = []) ⇒ Warray

init



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/warray.rb', line 9

def initialize(a = [])
  # Warray object has a stucture like this: [[value,weight],[value,weight]...]
  # @warray = Array.new { Array.new(2) }
  @warray = []
  # summerized weight for Warray object
  @wsum = 0
  # find the greatest common divisor, if there is not @gcd = 1
  @gcd = 1
  # use a temporary array to find the min weight
  j = []
  # flatten input array for avoid error
  a.flatten!
  # build Warray structure, odd items are values, even items are weights
  # make also sure that not give error if input array size is not even
  while a.size > 1
    value = a.shift
    weight =  a.shift.to_i.abs
    # summerize weights
    @wsum += weight
    # make sure that is it not null in array
    j << weight if weight != 0
    @warray << [value, weight]
  end
  # find the min weight and make gcd, if j is not empty
  @gcd = @wsum.gcd(j.min.to_i) unless j.empty?
  # return with [] if you call new method without array
  # otherwise return with Warray
  @warray
end

Instance Attribute Details

#gcdObject (readonly)

Returns the value of attribute gcd.



6
7
8
# File 'lib/warray.rb', line 6

def gcd
  @gcd
end

#sizeObject (readonly) Also known as: length

return with size of Warray object



40
41
42
# File 'lib/warray.rb', line 40

def size
  @size
end

#wsumObject (readonly)

Returns the value of attribute wsum.



6
7
8
# File 'lib/warray.rb', line 6

def wsum
  @wsum
end

Instance Method Details

#buildObject

build an array with weighted items



48
49
50
51
52
53
54
55
# File 'lib/warray.rb', line 48

def build
  a = []
  @warray.map do |i|
    a << Array.new((i[1] / @gcd), i[0])
  end
  # make sure that it is flatten
  a.flatten!
end