Stack two 3x3 matrices built from recycled vectors into a 3D array in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two R functions that turn numeric vectors of any length into 3x3 matrices and stack them into a 3D array. Inputs are recycled to length 9 with `rep_len` and filled column-major.
- `to_matrix_3x3(v)` returns a 3x3 numeric matrix where element (i, j) is `recycled[(j - 1) * 3 + i]`.
- `stack_two_matrices(v1, v2)` returns a numeric array with dim `c(3, 3, 2)`, where `result[, , 1]` is `to_matrix_3x3(v1)` and `result[, , 2]` is `to_matrix_3x3(v2)`.
- Both functions call `stop` if an input is non-numeric or has length 0.
For example:
```r
to_matrix_3x3(1:5)
# [,1] [,2] [,3]
# [1,] 1 4 2
# [2,] 2 5 3
# [3,] 3 1 4
a <- stack_two_matrices(1:5, c(10, 20))
dim(a) # 3 3 2
```
```hint Storage order
Check the order in which `matrix()` and `array()` place their values, and compare it with the index formula for element (i, j).
```
### Constraints & Assumptions
- Inputs can have any length. Valid inputs are numeric (integer or double) with at least one element.
- Vectors shorter than 9 are recycled, and vectors longer than 9 keep only their first 9 values.
### What a Strong Answer Covers
- Type and length validation that runs before any reshaping and is shared by both functions.
- Recycling to exactly 9 values for inputs both shorter and longer than 9.
- Why the default fill order matches the index formula `(j - 1) * 3 + i`.
- An array whose slices along the third dimension are exactly the two matrices, in order.
### Follow-up Questions
- How would you generalise this to stack an arbitrary number of vectors?
- What changes if each matrix must be filled row by row instead of column by column?
- `1:5` is an integer vector and `c(10, 20)` is double. What type does the stacked array have, and when would that matter?
Overview: Write two R functions that recycle a numeric vector of any length to 9 values, shape it into a column-major 3x3 matrix, and stack two such matrices into a 3 by 3 by 2 array. It tests rep_len, the fill order of matrix and array, and input validation with stop.