Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

ruby - Assign array elements randomly but ensure that all are used?

How can the assignment of array elements into different objects be randomised such that

  • there's no recycling of array elements (i.e. the same array element is never used more than once, unless it was a duplicate), and
  • all values get used, including duplicates. The resulting number of objects created should be the same as the length of the array
  • it works for array elements that aren't necessarily single integers

Example

An array [1, 2] would have two possible outcomes:

  1. a = 1 and b = 2, OR
  2. a = 2 and b = 1.

An array of [1, 2, 3] would have 6 possible outcomes.

Use case

I want to randomly sample inputs to a rails mailer preview, but the inputs aren't all of the same class, so I can't do something like Customer.all.sample

I also can't simply combine the possible inputs into an array and sample from it, since that could cause the same element to get used more than once.

question from:https://stackoverflow.com/questions/65877376/assign-array-elements-randomly-but-ensure-that-all-are-used

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.sample will sample without replacement by default.

So, for example,

arr = [1, 2, 3]

a, b, c = arr.sample(arr.length)

a
=> 3

b
=> 1

c
=> 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...