Class: BinPacker

Inherits:
Object
  • Object
show all
Defined in:
lib/histogram/bin_packer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bin_count, min, max) ⇒ BinPacker

Returns a new instance of BinPacker.



6
7
8
9
10
# File 'lib/histogram/bin_packer.rb', line 6

def initialize(bin_count, min, max)
  @bin_count = bin_count
  @max = max
  @min = min
end

Instance Attribute Details

#bin_countObject (readonly)

Returns the value of attribute bin_count.



4
5
6
# File 'lib/histogram/bin_packer.rb', line 4

def bin_count
  @bin_count
end

#maxObject (readonly)

Returns the value of attribute max.



4
5
6
# File 'lib/histogram/bin_packer.rb', line 4

def max
  @max
end

#minObject (readonly)

Returns the value of attribute min.



4
5
6
# File 'lib/histogram/bin_packer.rb', line 4

def min
  @min
end

Instance Method Details

#bin_widthObject



40
41
42
43
44
45
46
# File 'lib/histogram/bin_packer.rb', line 40

def bin_width
  if max.is_a?(Float) || min.is_a?(Float)
    (max - min) / bin_count.to_f
  else
    ((max - min) / bin_count.to_f).ceil
  end
end

#bins(values) ⇒ Object



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
38
# File 'lib/histogram/bin_packer.rb', line 12

def bins(values)
  groups = Array.new(bin_count) do |i|
    f = min + i * bin_width
    range_max = if f.is_a?(Integer)
      f + bin_width - 1
    else
      f + bin_width.prev_float
    end

    Bin.new(f..range_max, 0)
  end
  binmax = groups.last.range.max
  unless binmax >= max
    groups << if bin_width == 1
      Bin.new(max..max, 0)
    else
      Bin.new(binmax..(binmax + bin_width), 0)
    end
  end

  values.each do |v|
    bin = groups.detect { |bin| bin.range.include?(v) }
    bin.count += 1
  end

  groups
end