samedi 30 novembre 2019

PHP generate array of random numbers with conditions

Is there an easy way with PHP to generate an array with 15 items, all single digit numbers between 1 and 8, in random order, but with the conditions that no digit is next to itself and no pair of digits are next to themselves.

Want to end up with something like: 3 2 7 1 3 2 5 6 7 4 5 1 8 4 8

But not: 3 8 4 4 6 7 2 6 7 3 1 1 8 5 2

Or: 2 8 6 3 7 5 7 5 4 8 1 2 4 1 6

Plan B is to generate a bigger array and then compare the current value with the previous during the foreach function and if the same skip that one and move to the next. And I am guessing could do the same by comparing the last three to check for pairs. But then I risk some digits appearing too many times, as the ideal is each digit appearing at least once, but no more than 2 times.




Aucun commentaire:

Enregistrer un commentaire