Skip to content
Snippets Groups Projects
ListMatrix.java 1.63 KiB
Newer Older
  • Learn to ignore specific revisions
  • Guyslain's avatar
    Guyslain committed
    package matrix;
    
    
    BALME Maxence's avatar
    BALME Maxence 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) {
    
    BALME Maxence's avatar
    BALME Maxence committed
        this.width = width;
        this.height = height;
        this.matrix = new ArrayList<>(width);
    
    Guyslain's avatar
    Guyslain committed
        this.initializeWith(initializer); // fills the matrix using initializer
      }
    
      public ListMatrix(int width, int height, T constant) {
        this(width, height, new ConstantMatrixInitializer<>(constant));
      }
    
      private void initializeWith(MatrixInitializer<T> initializer) {
    
    BALME Maxence's avatar
    BALME Maxence committed
        for (int x=0; x<width; x++) {
          List<T> column = new ArrayList<>(height);
    
          for (int y = 0; y < height; y++) {
            column.add(initializer.initialValueAt(new Coordinate(x, y)));
          }
          matrix.add(column);
        }
    
        }
    
    
    Guyslain's avatar
    Guyslain committed
    
      public int width() {
    
    BALME Maxence's avatar
    BALME Maxence committed
        return width;
    
    Guyslain's avatar
    Guyslain committed
      }
    
      public int height() {
    
    BALME Maxence's avatar
    BALME Maxence committed
        return height;
    
    Guyslain's avatar
    Guyslain committed
      }
    
      @Override
      public T get(int x, int y) {
    
    BALME Maxence's avatar
    BALME Maxence committed
    
        return matrix.get(x).get(y);
    
    Guyslain's avatar
    Guyslain committed
      }
    
    
      @Override
      public void set(int x, int y, T newValue) {
    
    BALME Maxence's avatar
    BALME Maxence committed
        matrix.get(x).set(y,newValue);