Determine the amount of times a number can repeat in an array

Asked

Viewed 344 times

1

I need to create a draw system where a certain number will be required to appear 3 times in an array.

It has to have 9 random positions from 1 to 6 and only one number 1 can repeat 3 times, the others at most 2 times

Example: array(1,2,1,3,5,3,6,5,1);

The way I thought of working this totally inefficient, because I have no control of the number that will repeat, nor how many times

$numeros_jogadas = rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6).",".rand(1, 6);
  • 1

    You could post what you’ve already tried to do?

  • 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

  • 1

    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

  • 1

    @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

  • @Marcospaulo On the line gerado == 1 you can replace by any number.

  • You intend to do this for other numbers right? For example, number 1 repeats x, number 2 repeats y, etc...?

  • @Cypherpotato, the idea would be, but I think if I can get it with just one number it already fits me

  • A number is thank you to be repeated 3 times or until 3 times?

  • A number is required to repeat 3 times, could be a specific number = 1

Show 4 more comments

2 answers

2


An idea is already set from the beginning the number 3 times repeated and already include them in the array:

$num3 = rand(1, 6);
$array = array();
array_push($array,$num3,$num3,$num3);

Then make a while to fill the other 6 positions with random numbers other than the number that has already been set 3 times, and in the middle use a for to count how many occurrences of the new number is in the array, and only enter this new number if there are no more than 2 occurrences of it. See the full code with explanatory comments:

<?php
function nums(){

   $num3 = rand(1, 6); // número que irá se repetir 3 vezes
   $array = array(); // declara a array
   // insere o valor nas 3 primeiras posições da array
   array_push($array,$num3,$num3,$num3);

   // enquanto a areray não tiver 9 posições
   while(sizeof($array) < 9){
      // número aleatório de 1 a 6
      $num = rand(1, 6);

      // se este número for diferente do número repetido 3 vezes
      // se for igual, o while continua rodando
      if($num3 != $num){

         // contador para contar ocorrências
         $conta = 0;

         // verifica ocorrências do número
         for($x = 0; $x < sizeof($array); $x++){
            if($array[$x] == $num) $conta++;
         }

         // se houver menos de 2 ocorrências
         // adiciona o número na array
         if($conta < 2) $array[] = $num;

      }

   }

   // randomiza a ordem dos elementos
   shuffle($array);

   // retorna a array
   return $array;
}

// printa a array na tela
print_r(nums());
?>

See the IDEONE

After the array is formed with the 9 positions, the line shuffle($array); scrambles the elements. Test as many times as you want and realize that only 1 number has 3 occurrences, and the rest are different and can only be repeated at most 2 times.

1

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
]
  • Thanks @Jrd I was trying to recreate here, but always cracking the head, testing the code here, do not know pq local, it runs normally, but on the error server the initial array $arr = [1, 1, 1]; Can tell me pq?

  • Has more details of the bug @Marcospaulo?

  • So tell me you made an error on line 03 [22-Mar-2019 09:57:46 America/Sao_paulo] PHP Parse error: syntax error, Unexpected '[' in /home/fxcompco/public_html/raspadinha/Randon.php on line 3

  • 1

    It’s probably the php version, try switching to $arr = array(1, 1, 1);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.