Skip to content
Snippets Groups Projects
ListMatrix.java 1.74 KiB
Newer Older
  • Learn to ignore specific revisions
  • Guyslain's avatar
    Guyslain committed
    package matrix;
    
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
    import java.util.ArrayList;
    
    Guyslain's avatar
    Guyslain committed
    import java.util.List;
    
    
    /**
     * Represents a matrix, a rectangular array, with generic values in each cell.
     *
     * @param <T> The type of values stored in the matrix cells.
     */
    public class ListMatrix<T> implements Matrix<T> {
    
      private final List<List<T>> matrix;
      private final int width;
      private final int height;
    
      /**
       * Creates a new {@link ListMatrix} with the specified width, height, and an initializer to set
       * values.
       *
       * @param width       The width of the {@link ListMatrix}.
       * @param height      The height of the {@link ListMatrix}.
       * @param initializer A matrix initializer to set values in the {@link ListMatrix}.
       */
      public ListMatrix(int width, int height, MatrixInitializer<T> initializer) {
        this.width = 0;
        this.height = 0;
        this.matrix = null;
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        this.initializeWith(initializer);
    
        for (int i = 0; i < height; i++) {
          List<T> row = new ArrayList<>(width);
          for (int j = 0; j < width; j++) {
            row.add(null);
          }
          matrix.add(row);
        }
        this.initializeWith(initializer);
    
    Guyslain's avatar
    Guyslain committed
      }
    
      public ListMatrix(int width, int height, T constant) {
        this(width, height, new ConstantMatrixInitializer<>(constant));
      }
    
      private void initializeWith(MatrixInitializer<T> initializer) {
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        for (int i = 0; i < matrix.size(); i++) {
          for (int j = 0; j < matrix.get(i).size(); j++) {
            matrix.get(i).set(j, initializer.initialValueAt(Coordinate.of(i,j)));
          }
        }
    
    Guyslain's avatar
    Guyslain committed
      }
    
      public int width() {
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        return width;
    
    Guyslain's avatar
    Guyslain committed
      }
    
      public int height() {
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        return height;
    
    Guyslain's avatar
    Guyslain committed
      }
    
      @Override
      public T get(int x, int y) {
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        return matrix.get(x).get(y);
    
    Guyslain's avatar
    Guyslain committed
      }
    
    
      @Override
      public void set(int x, int y, T newValue) {
    
    POUSSARDIN Malo's avatar
    POUSSARDIN Malo committed
        matrix.get(x).set(y, newValue);