Using the idea presented in C# by @Cypherpotato I made the PHP implementation.
The idea is to put in a loop to generate the array of the 9 positions and go checking the amount of values already inserted and only insert if you have not yet reached the limit, if the value is added to the array the loop is incremented by +1.
$arr = array(1, 1, 1); //inicializa o array com o número obrigatório preenchido
$i = 4; //inicia o inteiro controlador da quantidade de posições preenchidas no array
//laço de repetição para garantir as 9 posições do array. O $i é incrementado sempre que for adicionado um valor ao array.
while($i <= 9){
$valor = rand(1, 6); //gera o valor randômico de 1 a 6
//Verifica se já teve alguma ocorrência do valor gerado no array
if(isset(array_count_values($arr)[$valor])){
//caso o valor gerado não seja 1, verifica se já teve as 2 ocorrências para esse valor. Caso não tenha as 2 ocorrências, adiciona o valor ao array
if(array_count_values($arr)[$valor] < 2){
array_push($arr, $valor);
$i++;
}
}else{
//Se ainda não houver nenhuma ocorrência para o valor, adiciona ele ao array diretamente
array_push($arr, $valor);
$i++;
}
}
shuffle($arr); //randomiza os valores do array
print_r($arr);
The array_count_values
count the occurrences of each position of the array and group, returning the value as an index and the quantity as the value of that index. Example:
$array = [1, 1, 3, 1, 2, 2];
The result of array_count_values
would be
print_r($arr);
[
1 => 3,
2 => 2,
3 => 1
]
Using as example this other array
$arr = ["banana", "maçã", "banana", "pêra", "banana", "pêra"];
We would have as a result of array_count_values
print_r($arr);
[
"banana" => 3,
"maçã" => 1,
"pêra" => 2
]
You could post what you’ve already tried to do?
– Vinicius Gabriel
I was trying in a random way, but then I realized that logic would need a specific number to repeat, so I got lost, I’ll edit and put what I tried
– Marcos Paulo
I was going to answer, but I didn’t see it was PHP and I wrote it in C#. But if you want to take a look, the code is here: https://dotnetfiddle.net/jWxK3t
– CypherPotato
@Cypherpotato, FIXING - And almost exactly what I need, I have only to determine the number that will be required to repeat I will see your logic and try to adapt to what I need with the functions of PHP
– Marcos Paulo
@Marcospaulo On the line
gerado == 1
you can replace by any number.– CypherPotato
You intend to do this for other numbers right? For example, number 1 repeats x, number 2 repeats y, etc...?
– CypherPotato
@Cypherpotato, the idea would be, but I think if I can get it with just one number it already fits me
– Marcos Paulo
A number is thank you to be repeated 3 times or until 3 times?
– Sam
A number is required to repeat 3 times, could be a specific number = 1
– Marcos Paulo