mruby-random (mrb_ary_sample): reduce the scope of loop variables

This commit is contained in:
Yukihiro "Matz" Matsumoto
2024-01-08 07:23:03 +09:00
parent 2cf6f7f5c7
commit 27c2f9ac38
+3 -4
View File
@@ -344,19 +344,18 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
}
else {
mrb_value result;
mrb_int i, j;
if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, "negative sample number");
if (n > len) n = len;
result = mrb_ary_new_capa(mrb, n);
for (i=0; i<n; i++) {
for (mrb_int i=0; i<n; i++) {
mrb_int r;
for (;;) {
retry:
r = rand_i(random, len);
for (j=0; j<i; j++) {
for (mrb_int j=0; j<i; j++) {
if (mrb_integer(RARRAY_PTR(result)[j]) == r) {
goto retry; /* retry if duplicate */
}
@@ -365,7 +364,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
}
mrb_ary_push(mrb, result, mrb_int_value(mrb, r));
}
for (i=0; i<n; i++) {
for (mrb_int i=0; i<n; i++) {
mrb_int idx = mrb_integer(RARRAY_PTR(result)[i]);
mrb_value elem = RARRAY_PTR(ary)[idx];
mrb_ary_set(mrb, result, i, elem);