Project

General

Profile

Feature #12775

Random subset of array

Added by sawa (Tsuyoshi Sawada) over 2 years ago. Updated about 2 years ago.

Status:
Feedback
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:77330]

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]

History

Updated by nobu (Nobuyoshi Nakada) over 2 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) over 2 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) over 2 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 2 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?

Also available in: Atom PDF