Project

General

Profile

Actions

Feature #12775

closed

Random subset of array

Added by sawa (Tsuyoshi Sawada) about 8 years ago. Updated about 3 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:77320]

Description

I often see use cases to randomly sample a subset from an array like this:

a = [3, 2, 6, 2, 6, 1]
a.sample(rand(a.length + 1)) # => [2, 6, 6, 3]

I request extending Array#sample to let it take an option (such as :arbitrary) for doing that:

a.sample(:arbitrary) # => [2, 6, 6, 3]

or perhaps having an independent method (like samples) to do it.

a.samples # => [2, 6, 6, 3]

Updated by nobu (Nobuyoshi Nakada) about 8 years ago

  • Status changed from Open to Feedback

Do you mean random size subset?
I can't get how/why it is useful.
Please elaborate with the use cases.

Updated by sawa (Tsuyoshi Sawada) about 8 years ago

Nobuyoshi Nakada wrote:

Do you mean random size subset?
I can't get how/why it is useful.
Please elaborate with the use cases.

Yes, I mean random subset with random size. The use cases are mainly for testing.

Updated by trans (Thomas Sawyer) about 8 years ago

This definition of #sample seems a bit limited. I know it aligns with the statical definition but it is very easy do another way: shuffle.take(n). Also, the interface is a little odd because it can return an element or an Array. Maybe it would be better if it could return repeats.

[1,2,3,4].sample(10) => [1,2,4,3,3,4,2,1,2,3]

Then #sample could also take a block and return an enumerator when given no argument. To get one element it would be sample.first.

But if backward compatibility needs to be preserved, then add this functionality by another name.

P.S. It would be weird but #sample could use negative numbers to allow repeating.

Updated by shyouhei (Shyouhei Urabe) about 8 years ago

We looked at this issue at todays developer meeting but a "random subset with random size" still does not sound familiar to the attendees.

Can you show us in code how do you use such array?

Updated by nobu (Nobuyoshi Nakada) about 3 years ago

  • Status changed from Feedback to Rejected

No feedback 5 years.
Feel free to re-open if you have any new points of view.

Updated by sawa (Tsuyoshi Sawada) about 3 years ago

Sorry for not responding for five years. I feel OK with it being closed.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0