Skip to content

Commit 0209afc

Browse files
authored
Merge pull request #22 from mrkn/fix_hist
histogram: Fill weights array by zeros before putting weight values
2 parents 6139604 + 3f96d3c commit 0209afc

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

ext/enumerable/statistics/extension/statistics.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2284,7 +2284,7 @@ ary_histogram(int argc, VALUE *argv, VALUE ary)
22842284
{
22852285
VALUE arg0, opts, edge, weights;
22862286
int left_p;
2287-
long nbins;
2287+
long nbins, nweights, i;
22882288

22892289
rb_scan_args(argc, argv, "01:", &arg0, &opts);
22902290
if (NIL_P(arg0)) {
@@ -2296,7 +2296,13 @@ ary_histogram(int argc, VALUE *argv, VALUE ary)
22962296
left_p = opt_closed_left_p(opts);
22972297

22982298
edge = ary_histogram_calculate_edge(ary, nbins, left_p);
2299-
weights = rb_ary_new_capa(RARRAY_LEN(edge) - 1);
2299+
2300+
nweights = RARRAY_LEN(edge) - 1;
2301+
weights = rb_ary_new_capa(nweights);
2302+
for (i = 0; i < nweights; ++i) {
2303+
rb_ary_store(weights, i, INT2FIX(0));
2304+
}
2305+
23002306
histogram_weights_push_values(weights, edge, ary, left_p);
23012307

23022308
return rb_struct_new(cHistogram, edge, weights,

spec/histogram/array_spec.rb

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
RSpec.describe Array, '#histogram' do
55
let(:ary) { [] }
66
let(:args) { [] }
7+
let(:kwargs) { {} }
78

8-
subject(:histogram) { ary.histogram(*args) }
9+
subject(:histogram) { ary.histogram(*args, **kwargs) }
910

1011
with_array [] do
1112
context 'default' do
@@ -18,7 +19,7 @@
1819
end
1920

2021
context 'closed: :right' do
21-
let(:args) { [{closed: :right}] }
22+
let(:kwargs) { {closed: :right} }
2223

2324
specify do
2425
expect(histogram.edge).to eq([0.0])
@@ -51,6 +52,19 @@
5152
end
5253
end
5354

55+
with_array [1, 2] do
56+
context 'closed: :left' do
57+
let(:kwargs) { {closed: :left} }
58+
59+
specify do
60+
expect(histogram.edge).to eq([1.0, 1.5, 2.0, 2.5])
61+
expect(histogram.weights).to eq([1, 0, 1])
62+
expect(histogram.closed).to eq(:left)
63+
expect(histogram.density?).to eq(false)
64+
end
65+
end
66+
end
67+
5468
with_array [1, 2, 3, 4, 5, 6, 7, 8, 9] do
5569
context 'default' do
5670
specify do
@@ -62,7 +76,7 @@
6276
end
6377

6478
context 'closed: :right' do
65-
let(:args) { [{closed: :right}] }
79+
let(:kwargs) { {closed: :right} }
6680

6781
specify do
6882
expect(histogram.edge).to eq([0.0, 2.0, 4.0, 6.0, 8.0, 10.0])
@@ -108,7 +122,7 @@
108122
end
109123

110124
context "closed: :right" do
111-
let(:args) { [{closed: :right}] }
125+
let(:kwargs) { {closed: :right} }
112126

113127
specify do
114128
expect(histogram.edge).to eq([-4.0, -3.5, -3.0, -2.5, -2.0, -1.5,

0 commit comments

Comments
 (0)