PHP - How to find the least common element in an array

Asked

Viewed 300 times

2

The job is to create 2 arrays with random numbers between 0 and 30. These 2 arrays should be drawn from the most common element to the least common.

Next I have to show to the screen the most common, least common element and which numbers from 0 to 30 are missing in the two arrays.

Right now I can show the screen the most common element, my doubt is on how to discover the least common.

I have already done research on the various functions of Sort (arsort, asort, krsort, etc) but still could not proceed.

The code I have is this::

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">

        <title>
            Totally not a legit website
        </title>

    </head>

    <body>

        <?php
            function veto($min, $max) {

                for ($i = 0; $i < 10; $i++){
                    $array1[$i] = rand($min, $max);
                    $array2[$i] = rand($min, $max);
                }

                // print_r($array1);
                // print_r($array2);      

            $count_1 = array_count_values($array1);
            $count_2 = array_count_values($array2);

            arsort($count_1); // sortear 
            arsort($count_2); // descendente

            $first_array1 = key($count_1); //mais repetido do array1
            $first_array2 = key($count_2); //mais repetido do array2

//------------------------------------------------------------------------------------------------
            $count_first_1 = current($count_1);
            $count_second_1 = next($count_1);   

            if($count_first_1 != $count_second_1) { // para saber se existem repetidos no 1º lugar
                echo $first_array1 . ' mais comum no primeiro array';
                echo "</br>";
            } else {
                echo $first_array1 . ' - input repetido no mais comum';
                echo "</br>"; 
            }          
//-------------------------------------------------------------------------------------------------
            $count_first_2 = current($count_2);
            $count_second_2 = next($count_2);   

            if($count_first_2 != $count_second_2) { // para saber se existem repetidos no 1º lugar
                echo $first_array2 . ' mais comum no segundo array';
                echo "</br>";
            } else {
                echo $first_array2 . ' - input repetido no mais comum';
                echo "</br>";
            }


            print_r ($array1);     
            echo "</br>";
            print_r ($array2);      
            echo "</br>";

            // print_r(end($count_1));
            // echo "</br>";
            // echo print_r(end($count_2));   
            // echo "</br>";


        }

            $min = 0;
            $max = 30;  

            veto($min, $max);
        ?>

    </body>
</html>

Thanks in advance.

  • I just don’t understand, the element that least appears should be compared in an array or two? I mean vc will 2 numbers (1 per array) 'less frequent'

  • Yes, 2 numbers, 1 for each array and yes, it is compared each one in its array.

1 answer

2


I decided to break the logic into three parts (functions) the first is how to assemble the array of selected numbers, the second the display of the largest and smallest and the last check which numbers have not been selected but which are in the range informed.

function gerarNumeros($min, $max) {
    $arr = array();

    for ($i = 0; $i < 10; $i++){
        $arr[] = rand($min, $max);
    }

    return array_count_values($arr);
}

The idea of this function is to return an array where the index is the number generated by rand() and the value is amount of times he appeared who does that is the function array_count_values()

The exit is something like:

Array
(
    [13] => 1
    [11] => 3
    [7] => 1
    [4] => 1
    [8] => 1
    [15] => 1
    [6] => 1
    [10] => 1
)

function obterMaiorEMenor($arr){
    $maior = sprintf('O número: %s apareceu %s vezes', array_search(max($arr), $arr, true), max($arr));
    $menor = sprintf('O número: %s apareceu %s vez', array_search(min($arr), $arr, true), min($arr));
    return array('maior' => $maior, 'menor' => $menor);
}

The above function receives the generated array and uses the functions max() and min() to get the largest and smallest value present in the array. Detail in the case of equal quantities, the first element found shall be considered to be the largest or the smallest.

function numerosDeFora($min, $max, $arr){
    return array_diff(range($min, $max), $arr);
}

Finally this function calculates the difference between all the diponable numbers (range($min, max) and those selected ($arr) and returns a new array.

Execution of the code:

$a = gerarNumeros(1, 15);
$extremos = obterMaiorEMenor($a);

$numeros = array_keys($a); //Lembre que os números são os índices e as quantidades os valores
sort($numeros); //classifica do menor para o maior


echo $extremos['maior'] .'<br>'. $extremos['menor'];

echo '<br>Números selecionados: '. implode(', ', array_unique($numeros));
echo '<br>Números de fora: '. implode(', ', numerosDeFora(1, 15, $numeros));

Exit:

O número: 11 apareceu 3 vezes
O número: 13 apareceu 1 vez
Números selecionados: 4, 6, 7, 8, 10, 11, 13, 15
Números de fora: 1, 2, 3, 5, 9, 12, 14
  • I understood but I was left with a doubt in the function to get more. At the last part where you define "Return array('greater' => $greater, 'lesser' => $less);" is there any specific reason for terms to write 'greater' => $greater ? You could no longer write down "echo $extremes[$bigger] . '<br>'. $extremes[$smaller]; " ? If the doubt is basic I would accept tbm to show me where I can clarify (I started studying php at university this year)

  • @Xiri_ can yes, in this case it was only to facilitate formatting.

Browser other questions tagged

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