Pergunta de entrevista da empresa Cruise

Construct a dense matrix class in C++ with add and multiply operators.

Respostas da entrevista

Sigiloso

15 de ago. de 2019

#include using namespace std; class matrix { int rows; int cols; int *buf; public: matrix() {rows = 0; cols = 0; buf = NULL;} matrix(int r, int c) { rows = r; cols = c; buf = (int *) new int[rows*cols]; } ~matrix() { rows = 0; cols = 0; if (buf)delete buf; } void fill_matrix() { int i = 0, j = 0; cout > buf[i*cols + j]; } } } void print_matrix() { int i = 0, j = 0; for (i=0; i < rows; i++) { for (j=0; j < cols; j++) { cout << buf[i*cols + j]; cout << "\t"; } cout << endl; } } matrix operator+ (const matrix& m) { int i,j; matrix r(m.rows,m.cols); if ((m.cols != cols) || (m.rows != rows)) { cout << "Invalid operation" << endl; } else { for (i=0; i < rows; i++) for (j=0; j < cols; j++) r.buf[i*cols + j] = buf[i*cols + j] + m.buf[i*cols + j]; } return r; } matrix operator* (const matrix& m) { int i,j,k, sum; matrix r(rows, m.cols); if (m.rows != cols) { cout << "Invalid operation" << endl; } else { for (i=0; i < rows; i++) for(j=0; j < m.cols; j++) { r.buf[i*r.cols + j] = 0; for(k=0; k < m.rows; k++) { r.buf[i*r.cols + j] += buf[i*cols + k] * m.buf[k*m.cols + j]; } } } return r; } };

1

Sigiloso

15 de out. de 2017

Created a templated class using std::vector and row-based one-dimensional indexing. I ran out of time to implement the multiply operator.