mardi 1 novembre 2022

Get n number of random values from an array and prevent consecutively repeated values

I want to populate a result array containing values randomly drawn from an input array, but the result array must not have two identical consecutive values.

Additional rules:

  1. The input array of values will contain only unique values and will have at least two values to ensure that it is possible to populate the required result array.
  2. The number of random values may be more or less than the size of the input array.
  3. The result array must not require that all values from the input are used if the number of random values is greater than the input array's size. In other words, the randomly selected values must not be biased for even distribution.

Sample input:

$array = ['one', 'two', 'three', 'four'];
$n = 10;

A non-exhaustive list of possible valid results:

  • ["three","one","three","one","two","one","four","one","three","four"]

  • ["four","three","two","one","two","four","one","three","two","one"]

  • ["two","four","three","one","two","one","four","two","three","one"]


This question was inspired by this deleted question which struggled to ask the question with clear rules and expectations.




Aucun commentaire:

Enregistrer un commentaire