Skip to content

Commit d678348

Browse files
committed
histogram: Fill weights array by zeros before putting weight values
Fix #21
1 parent 6139604 commit d678348

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
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: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,19 @@
5151
end
5252
end
5353

54+
with_array [1, 2] do
55+
context 'closed: :left' do
56+
let(:args) { [{closed: :left}] }
57+
58+
specify do
59+
expect(histogram.edge).to eq([1.0, 1.5, 2.0, 2.5])
60+
expect(histogram.weights).to eq([1, 0, 1])
61+
expect(histogram.closed).to eq(:left)
62+
expect(histogram.density?).to eq(false)
63+
end
64+
end
65+
end
66+
5467
with_array [1, 2, 3, 4, 5, 6, 7, 8, 9] do
5568
context 'default' do
5669
specify do

0 commit comments

Comments
 (0)