1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| <?php
/**
* Génération d'une matrice carrée
* @param $size Taille de la matrice
* @return Tableau à 2 dimensions représentant la matrice
*/
function get_matrix($size) {
$matrix = array();
$row = array();
for ($i = 1; $i <= $size * $size; $i++) {
$row[] = $i;
if ( $i % $size == 0 ) {
$matrix[] = $row;
$row = array();
}
}
return $matrix;
}
/**
* Tableau des voisins d'un nombre dans une matrice
* @param $matrix Matrice (tableau à 2 dimensions)
* @param $size Taille de la matrice carrée
* @param $i Nombre à prendre en compte
* @return Tableau de voisin du nombre dans la matrice
*/
function get_neighbors($matrix, $size, $i) {
// Coordonnées du nombre dans la matrice
$row = ceil($i / $size) - 1;
$column = ( $i - 1 ) % $size;
// Initialisation du tableau des voisins
$neighbors = array();
// Ajoute les éléments de la ligne du dessus
if ( isset($matrix[$row - 1]) ) {
$top = $matrix[$row - 1];
if ( isset($top[$column - 1]) ) $neighbors[] = $top[$column - 1];
if ( isset($top[$column]) ) $neighbors[] = $top[$column];
if ( isset($top[$column + 1]) ) $neighbors[] = $top[$column + 1];
}
// Ajoute les éléments de la ligne centrale
$middle = $matrix[$row];
if ( isset($middle[$column - 1]) ) $neighbors[] = $middle[$column - 1];
if ( isset($middle[$column + 1]) ) $neighbors[] = $middle[$column + 1];
// Ajoute les éléments de la ligne du dessous
if ( isset($matrix[$row + 1]) ) {
$bottom = $matrix[$row + 1];
if ( isset($bottom[$column - 1]) ) $neighbors[] = $bottom[$column - 1];
if ( isset($bottom[$column]) ) $neighbors[] = $bottom[$column];
if ( isset($bottom[$column + 1]) ) $neighbors[] = $bottom[$column + 1];
}
return $neighbors;
}
$size = 4; // Taille de la matrice
$matrix = get_matrix($size);
for ($i = 1; $i <= $size * $size; $i++) {
$neighbors = get_neighbors($matrix, $size, $i);
echo '<p>';
echo $i;
echo ' : ';
echo implode(', ', $neighbors);
echo '</p>';
}
?> |
Partager