Skip to content
Snippets Groups Projects
Commit bd34ce06 authored by Yanis O's avatar Yanis O
Browse files

[Modif] Changement de Matrix, afin de supporter les matrices non carré

parent 5f0836f8
No related branches found
No related tags found
No related merge requests found
......@@ -6,26 +6,89 @@ import java.util.NoSuchElementException;
public class Matrix<E> implements Iterable<E> {
private ArrayList<ArrayList<E>> matrix;
private final int rows;
private final int columns;
public Matrix() {
this.matrix = new ArrayList<ArrayList<E>>();
public Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.matrix = new ArrayList<>(rows);
// Initialiser chaque ligne de la matrice
for (int i = 0; i < rows; i++) {
ArrayList<E> row = new ArrayList<>(columns);
// Initialiser chaque colonne avec des valeurs nulles
for (int j = 0; j < columns; j++) {
row.add(null);
}
this.matrix.add(row);
}
}
public E get(int x, int y) {
validateIndexes(x, y);
return matrix.get(x).get(y);
}
public E set(int x, int y, E object) {
validateIndexes(x, y);
return matrix.get(x).set(y, object);
}
public void clear() {
this.matrix = new ArrayList<ArrayList<E>>();
this.matrix.clear();
for (int i = 0; i < rows; i++) {
ArrayList<E> row = new ArrayList<>(columns);
for (int j = 0; j < columns; j++) {
row.add(null);
}
this.matrix.add(row);
}
}
public int size() {
return matrix != null ? matrix.get(0).size() * matrix.size() : 0;
return rows * columns;
}
public int getColumns(){
return this.columns;
}
public int getRows(){
return this.rows;
}
public void displayMatrix() {
System.out.print(" ");
for (int j = 0; j < columns; j++) {
System.out.print("___ ");
}
System.out.println();
for (int i = 0; i < rows; i++) {
System.out.print("| ");
for (int j = 0; j < columns; j++) {
if (matrix.get(i).get(j) != null) {
System.out.print(" x | ");
} else {
System.out.print(" | ");
}
}
System.out.println();
System.out.print(" ");
for (int j = 0; j < columns; j++) {
System.out.print("___ ");
}
System.out.println();
}
}
private void validateIndexes(int x, int y) {
if (x < 0 || x >= rows || y < 0 || y >= columns) {
throw new IndexOutOfBoundsException("Indices x: "+ x + " y: " + y + " hors limites pour la matrice.");
}
}
@Override
public Iterator<E> iterator() {
......@@ -38,7 +101,7 @@ public class Matrix<E> implements Iterable<E> {
@Override
public boolean hasNext() {
return row < matrix.size() && col < matrix.get(row).size();
return row < rows && col < columns;
}
@Override
......@@ -48,7 +111,7 @@ public class Matrix<E> implements Iterable<E> {
}
E element = matrix.get(row).get(col);
col++;
if (col >= matrix.get(row).size()) {
if (col >= columns) {
col = 0;
row++;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment