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:
- a = 1 and b = 2, OR
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…