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

1

Assuming I have an array like this:

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

I'm trying to make a way to get an array with the key-value pairs, but randomly without the 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 in both the key and the 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 fine, but it has time that it does not go while , it reaches the maximum execution time.

    
asked by anonymous 30.10.2015 / 22:13

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 only to highlight, the odds are low but it could happen that all numbers are drawn, and the last remaining value is the same as the last key, thus generating an error. For this use of do{}while($reset);

    
09.11.2015 / 20:27