Voici une classe qui permet la rotation matricielle simple en PHP.
class Matrix { function rotateClockwise90( $matrix ) { $newMatrix = array(); foreach( $matrix as $line ) { foreach( $line as $k => $v ) { if( !isset( $newMatrix[ $k ] ) ) { $newMatrix[ $k ] = array(); } array_unshift( $newMatrix[ $k ], $v ); } } return $newMatrix; } function rotateClockwise180( $matrix ) { return $this->rotateClockwise90( $this->rotateClockwise90( $matrix ) ); } function rotateClockwise270( $matrix ) { return $this->rotateClockwise180( $this->rotateClockwise90( $matrix ) ); } } |
Un exemple d’utilisation:
function displayMatrix( $matrix ) { foreach( $matrix as $line ) { echo implode( ',', $line ) . PHP_EOL; } } $matrice = array( array( 'A','B','C' ), array( 'D','E','F' ), array( 'G','H','I' ), array( 'J','K','L' ) ); displayMatrix( $matrice ); echo PHP_EOL; $matrix = new Matrix(); $matrice = $matrix->rotateClockwise90( $matrice ); displayMatrix( $matrice ); |
Résultat avant la rotation:
A,B,C D,E,F G,H,I J,K,L
Résultat après la rotation:
J,G,D,A K,H,E,B L,I,F,C
Maintenant, vous me direz: « Qu’est-ce que je peux bien faire avec ça ? »… à suivre.