Matrix challenges are popular. There's an issue of how to provide test cases. A common method is the row-wise array-of-arrays representation, such as:
[[1,2],[3,4],[5,6]] -> a 3 by 2 matrix
This is good with vertical space, but there's always the task of converting the test cases into something your language can use, and vice versa for producing test cases to this format.
So this is a code-golf challenge and also a repository of conversion functions that people can use when trying or composing matrix challenges.
Defining the format
A row string of length m is a comma-separated list of m ≥ 1 numbers, enclosed in square brackets.
A row-wise n×m array-of-arrays string is a comma-separated list of n ≥ 1 row strings of length m enclosed in square brackets with the following whitespace rules:
- has no whitespace before the first
[or after the last
], except for an optional trailing newline.
- otherwise may contain spaces
Produce two* programs/functions in your language:
one which takes a rowwise n×m array-of-arrays string as an input, and outputs the matrix (as implemented in the language.)
another one which takes an n×m matrix (as implemented in the language) as an input and outputs the rowwise n×m array-of-arrays string.
*It is allowed for one program/function to perform both tasks and you can have helper code used by both conversion functions.
- To be clear: the language must support matrices (or something equivalent like 2D arrays - the name is not important) because the output/input of the two tasks needs to be an actual matrix in the language.
- This is code-golf.
- Fewest total number of bytes (from all functions and any helper code) in each language wins.
- If one program or function does both conversions, only count those bytes once.
- Standard rules apply/loopholes forbidden.
[] [ [ 1, 2 ], [ 3, 4 ] ] [[1.2,3.4,5.6],[3,2,1], [10, 11, 12.1]]
Not really possible to provide test matrices.
A non-golfed, possibly not bug-free worked example
I hope this doesn't violate the "don't answer your own question" guideline.
The R function I use to convert from string to matrix
The R function I use to convert from matrix to string