una rotar rotacion matriz matrices izquierda grados con arreglo php arrays rotation shift

rotacion - PHP: ''rotar'' una matriz?



rotar un arreglo en c++ (12)

Es muy simple y se podría hacer de muchas maneras. Ejemplo:

$array = array( ''a'', ''b'', ''c'' ); $array[] = array_shift( $array );

¿Es posible "rotar" fácilmente una matriz en PHP?

Así: 1, 2, 3, 4 -> 2, 3, 4, 1

¿Hay algún tipo de función PHP incorporada para esto?


Hacer un bucle a través de la matriz, y shift y push , puede ser una forma común de rotar una matriz, sin embargo, a menudo puede estropear las teclas. Un método más robusto es usar una combinación de array_merge y array_splice .

/** * Rotates an array. * * Numerical indexes will be renumbered automatically. * Associations will be kept for keys which are strings. * * Rotations will always occur similar to shift and push, * where the number of items denoted by the distance are * removed from the start of the array and are appended. * * Negative distances work in reverse, and are similar to * pop and unshift instead. * * Distance magnitudes greater than the length of the array * can be interpreted as rotating an array more than a full * rotation. This will be reduced to calculate the remaining * rotation after all full rotations. * * @param array $array The original array to rotate. * Passing a reference may cause the original array to be truncated. * @param int $distance The number of elements to move to the end. * Distance is automatically interpreted as an integer. * @return array The modified array. */ function array_rotate($array, $distance = 1) { settype($array, ''array''); $distance %= count($array); return array_merge( array_splice($array, $distance), // Last elements - moved to the start $array // First elements - appended to the end ); } // Example rotating an array 180°. $rotated_180 = array_rotate($array, count($array) / 2);

Alternativamente, si también encuentra la necesidad de rotar las claves para que coincidan con diferentes valores, puede combinar array_keys , array_combine , array_rotate y array_values .

/** * Rotates the keys of an array while keeping values in the same order. * * @see array_rotate(); for function arguments and output. */ function array_rotate_key($array, $distance = 1) { $keys = array_keys((array)$array); return array_combine( array_rotate($keys, $distance), // Rotated keys array_values((array)$array) // Values ); }

O alternativamente, gire los valores mientras mantiene las teclas en el mismo orden (equivalente a llamar a la distancia negativa en la llamada de la función array_rotate_key correspondiente).

/** * Rotates the values of an array while keeping keys in the same order. * * @see array_rotate(); for function arguments and output. */ function array_rotate_value($array, $distance = 1) { $values = array_values((array)$array); return array_combine( array_keys((array)$array), // Keys array_rotate($values, $distance) // Rotated values ); }

Y, por último, si desea evitar la renumeración de índices numéricos.

/** * Rotates an array while keeping all key and value association. * * @see array_rotate(); for function arguments and output. */ function array_rotate_assoc($array, $distance = 1) { $keys = array_keys((array)$array); $values = array_values((array)$array); return array_combine( array_rotate($keys, $distance), // Rotated keys array_rotate($values, $distance) // Rotated values ); }

Podría ser beneficioso realizar algunas pruebas de referencia, sin embargo, espero que un pequeño puñado de rotaciones por solicitud no afecte notablemente el rendimiento, independientemente del método que se utilice.

También debería ser posible rotar una matriz utilizando una función de clasificación personalizada, pero lo más probable es que sea demasiado complicado. es decir, usort .


Hay una tarea sobre la rotación de matrices en Hackerrank: https://www.hackerrank.com/challenges/array-left-rotation/problem .

Y la solución propuesta con array_push y array_shift funcionará para todos los casos de prueba excepto el último, que falla debido a un tiempo de espera. Por lo tanto, array_push y array_shift le darán la solución más rápida.

Aquí está el enfoque más rápido:

function leftRotation(array $array, $n) { for ($i = 0; $i < $n; $i++) { $value = array[$i]; unset(array[$i]); array[] = $value; } return array; }


La lógica es intercambiar los elementos. Algoritmo puede verse como

for i = 0 to arrayLength - 1 swap( array[i], array[i+1] ) // Now array[i] has array[i+1] value and // array[i+1] has array[i] value.


La mayoría de las respuestas actuales son correctas, pero solo si no te importan tus índices:

$arr = array(''foo'' => ''bar'', ''baz'' => ''qux'', ''wibble'' => ''wobble''); array_push($arr, array_shift($arr)); print_r($arr);

Salida:

Array ( [baz] => qux [wibble] => wobble [0] => bar )

Para preservar tus índices puedes hacer algo como:

$arr = array(''foo'' => ''bar'', ''baz'' => ''qux'', ''wibble'' => ''wobble''); $keys = array_keys($arr); $val = $arr[$keys[0]]; unset($arr[$keys[0]]); $arr[$keys[0]] = $val; print_r($arr);

Salida:

Array ( [baz] => qux [wibble] => wobble [foo] => bar )

Quizás alguien pueda hacer la rotación más sucintamente que mi método de cuatro líneas, pero esto funciona de todos modos.


No. Consulte la documentación de array_shift y sus funciones relacionadas para conocer algunas herramientas que puede usar para escribir una. Incluso podría haber una función array_rotate implementada en los comentarios de esa página.

También vale la pena leer a través de las funciones de matriz enumeradas en la barra lateral izquierda para obtener una comprensión completa de qué funciones de matriz están disponibles en PHP.



Puedes usar esta función:

function arr_rotate(&$array,$rotate_count) { for ($i = 0; $i < $rotate_count; $i++) { array_push($array, array_shift($array)); } }

uso:

$xarr = array(''1'',''2'',''3'',''4'',''5''); arr_rotate($xarr, 2); print_r($xarr);

resultado:

Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 1 [4] => 2 )


Un método para mantener las teclas y rotar. usando el mismo concepto que array_push (array, array_shift (array)), en su lugar usaremos array_merge de 2 array_slices

$x = array("a" => 1, "b" => 2, "c" => 3, ''d'' => 4);

Para mover el primer elemento al final.

array_merge(array_slice($x, 1, NULL, true), array_slice($x, 0, 1, true) //''b''=>2, ''c''=>3, ''d''=>4, ''a''=>1

Para mover el último elemento al frente.

array_merge(array_slice($x, count($x) -1, 1, true), array_slice($x, 0, //''d''=>4, ''a''=>1, ''b''=>2, ''c''=>3



$numbers = array(1,2,3,4); array_push($numbers, array_shift($numbers)); print_r($numbers);

Salida

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 1 )


$daynamesArray = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); array_push($daynamesArray, array_shift($daynamesArray)); //shift by one array_push($daynamesArray, array_shift($daynamesArray)); //shift by two print_r($daynamesArray);

La salida comienza en "miércoles":

Array ( [0] => Wednesday [1] => Thursday [2] => Friday [3] => Saturday [4] => Sunday [5] => Monday [6] => Tuesday