/* Manipulations sur une matrice de char */ public class ManipulationsMatriceCaractere { /* Fonction de creation et retour d'une matrice */ /* de caractere initialisee */ /* avec des caracteres minuscules aleatoires */ /* lignes : Le nombre de lignes */ /* colonnes : Le nombre de colonnes */ static char [][] initRandMatrice(int lignes,int colonnes) { char [][] tab = new char[lignes][colonnes]; for ( int i = 0 ; i < lignes ; i++ ) { for ( int j = 0 ; j < colonnes ; j++ ) { tab[i][j] =(char) ('a'+Math.random()*26.0); } } return tab; } /* Fonction d'affichage des valeurs contenues */ /* dans une matrice de caracteres */ /* t : La matrice à afficher */ static void affichageMatrice(char [][] t) { for ( int i = 0 ; i < t.length ; i++ ) { for ( int j = 0 ; j < t[0].length ; j++ ) { Ecran.afficher(t[i][j]); } Ecran.sautDeLigne(); } } /* Fonction d'affichage des valeurs contenues */ /* dans un tableau de caracteres */ /* t : Le tableau à afficher */ static void affichageTableau(char [] t) { for ( int i = 0 ; i < t.length ; i++ ) { Ecran.afficher(t[i]); } Ecran.sautDeLigne(); } ////////////////////////////////////////////////// /* Fonction de calcul et retour du tableau */ /* de caracteres obtenu par linéarisation */ /* d'une matrice de carateres */ /* t : La matrice à linéariser */ static char [] transformationEnTableau(char [][] t) { char [] res = new char[t.length*t[0].length]; int i = 0; for ( int l = 0 ; l < t.length ; l++ ) { for ( int c = 0 ; c < t[0].length ; c++ ) { res[i] = t[l][c]; i++; } } return res; } /* Fonction de calcul et retour de la matrice */ /* de caracteres obtenue par transformation */ /* en matrice d'un tableau de carateres */ /* t : Le tableau à transformer */ /* lignes : Le nombre de lignes */ /* de la matrice créée */ /* colonnes : Le nombre de colonnes */ /* de la matrice créée */ static char [][] transformationEnMatrice(char [] t, int lignes, int colonnes) { char [][] res = new char[lignes][colonnes]; if ( lignes*colonnes <= t.length ) { int i = 0; for ( int l = 0 ; l < lignes ; l++ ) { for ( int c = 0 ; c < colonnes ; c++ ) { res[l][c] = t[i]; i++; } } } else { int l = 0; int c = 0; for ( int i = 0 ; i < lignes*colonnes ; i++ ) { if ( i < t.length ) { res[l][c] = t[i]; } else { res[l][c] = ' '; } c++; if ( c == colonnes ) { c = 0; l++; } } } return res; } ////////////////////////////////////////////////// /* Programme principal */ public static void main(String [] args) { char [][] m = initRandMatrice(3,5); Ecran.afficherln("Matrice 3x5 initiale"); affichageMatrice(m); Ecran.sautDeLigne(); char [] t = transformationEnTableau(m); Ecran.afficherln("Tableau obtenu par transformation en tableau"); affichageTableau(t); Ecran.sautDeLigne(); char [][] m2 = transformationEnMatrice(t,4,6); Ecran.afficherln("Matrice obtenue transformation en matrice"); affichageMatrice(m2); } }