Task

Build an   identity matrix   of a size known at run-time.



An identity matrix is a square matrix of size n × n,

where the diagonal elements are all 1s (ones),

and all the other elements are all 0s (zeroes).







I

n


=


[



1


0


0


⋯


0




0


1


0


⋯


0




0


0


1


⋯


0




⋮


⋮


⋮


⋱


⋮




0


0


0


⋯


1



]




{\displaystyle I_{n}={\begin{bmatrix}1&0&0&\cdots &0\\0&1&0&\cdots &0\\0&0&1&\cdots &0\\\vdots &\vdots &\vdots &\ddots &\vdots \\0&0&0&\cdots &1\\\end{bmatrix}}}





Related tasks

   Spiral matrix
   Zig-zag matrix 
   Ulam_spiral_(for_primes)


class IdentityMatrix {
  function : Matrix(n : Int) ~ Int[,] {
    array := Int->New[n,n];
 
    for(row:=0; row<n; row+=1;){
      for(col:=0; col<n; col+=1;){
        if(row = col){
          array[row, col] := 1;
        }
        else{
          array[row,col] := 0;
        };
      };
    };
    return array;
  }
 
  function : PrintMatrix(array : Int[,]) ~ Nil {
    sizes := array->Size();
    for(row:=0; row<sizes[0]; row+=1;){
      for(col:=0; col<sizes[1]; col+=1;){
        value := array[row,col];
        "{$value} \t"->Print();
      };
      '\n'->PrintLine();
    };
  }
 
  function : Main(args : String[]) ~ Nil {
    PrintMatrix(Matrix(5));
  }
}
 