Hay.Flow
Hay.Flow

Reputation: 33

Creating a matrix out of a given vector

I'm having trouble with splitting up a vector into a 2D matrix or a given side. For example, given the vector {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, the rows (3), and columns (4) can be turned into {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}.

As of right now, the code just prints out the entire vector in a an array for however many rows their are.

int[][] reshape(int[] vector, int row, int col) {
        if (!isReshapable(vector.length, row, col)) {
            return null;
        } else {
            int[][] matrix = new int[row][col];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    Arrays.fill(matrix, vector);
                }
            }
            return matrix;
        }
    }    

Upvotes: 3

Views: 675

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201467

You're iterating both i and j. You could use them (and the position in the vector) with something like,

int p = 0;
int[][] matrix = new int[row][col];
for (int i = 0; i < row; i++) {
    for (int j = 0; j < col; j++, p++) {
        matrix[i][j] = vector[p];
    }
}

Upvotes: 1

Related Questions