I need a function that randomizes an array similar to what shuffle does, with the difference that each element has different chances.
For example, consider the following array:
$animals = array('elephant', 'dog', 'cat', 'mouse');
elephant has an higher chance of getting on the first index than dog. Dog has an higher chance than cat and so on. For example, in this particular example elephant could have a chance of 40% in getting in the 1st position, 30% of getting on the 2nd position, 20% on getting on 3rd and 10% getting on last.
So, after the shuffling, the first elements in the original array will be more likely (but not for sure) to be in the first positions and the last ones in the last positions.
Normal shuffle may be implemented just as
We can adjust dropping step, drop every element not into whole range, but at some sliding window. Let
Nwould be amount of elements in array, window width would bewand we’ll move it at each step byoff. Thenoff*(N-1) + wwould be total width of the range.Here’s a function, which distorts elements’ positions, but not completely at random.
$strength = 0~normal shuffle.$strength = 0.25~your desired result (40.5%, 25.5%, 22%, 12% forelephant)$strength = 1first item will never be after last one.$strength >= 3array is actually never shuffledPlayground for testing: