Same numbers in the key-value pair of an array, but random

Asked

Viewed 46 times

1

Assuming I have one array in this way:

array(10, 11, 12, 13, 14, 15)

I’m trying to make a way to get as a result, a array with key-value pairs, but randomly without pairs being equal. For example:

Valid

array(
    10 => 14,
    11 => 12,
    12 => 15,
    13 => 10,
    14 => 11,
    15 => 13
)

Not valid

array(
    10 => 14,
    11 => 11, // Não pode
    12 => 15,
    13 => 10,
    14 => 12,
    15 => 13
)

The second is not valid because the second position has the same value 11 both in key and in value.

My attempt was this:

$result = array();

$array = array(10, 11, 12, 13, 14, 15);
$copy = array(10, 11, 12, 13, 14, 15);

foreach ($array as $a) {
    $b = array_rand($copy, 1);

    while (!in_array($copy[$b], $result)) {
        if ($a != $copy[$b])
            $result[$a] = $copy[$b];
        else
            $b = array_rand($copy, 1);
    }

    unset($copy[$b]);
}

It often works, but there’s a time when he doesn’t leave the while, then reaches the maximum execution time.

1 answer

1


My development was as follows :

$array = array(10,11,12,13,14,15,16,17,18,19,20);
if(count($array) > 1){
    do{

        $flip = array_flip($array);
        $newArray = array();

        $reset = false;
        foreach ($flip as $key => $value){
            $range = $flip;                 # COPIA FLIP PARA O RANGE A SER TRATADO
            unset($range[$key]);                # REMOVE A CHAVE ATUAL DO RANGE

            if(!$range){                       # VERIFICA SE O ARRAY ESTA VAZIO
                $reset = true;                 # - PODE OCORRER NA ULTIMA CHAVE
                break;                        # - RESETA PARA INICIAR DO 0
            }

            $range = array_keys($range);        # CRIA UM ARRAY APENAS COM OS VALORES DISPONIVEIS
            $rand = rand(0, count($range)-1);   # SORTEIA UM VALOR A SER COPIADO
            $value = $range[$rand];          # CAPTURA O VALOR
            $newArray[$key] = $value;        # SETA O NOVO ARRAY COM A CHAVE E O VALOR SORTIADO
            unset($flip[$value]);               # REMOVE O VALOR SORTIADO DAS PROXIMAS ESCOLHAS
        }
    }while($reset);
}

The code is already explained, but just to highlight, the chances are low but it could occur that all numbers are drawn, and the last remaining value is the same as the last key, thus generating error. 'Cause that’s the use of do{}while($reset);

  • Perfect, everything worked out in the test. Thank you!

Browser other questions tagged

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