# Simplify matrix input!

I have written a few challenges related to matrices, and common for all are that I use a format like the one below when representing the matrices, both in examples and in test cases:

16    2    3   13
5   11   10    8
9    7    6   12
4   14   15    1


This is likely a cumbersome format in many languages.

# Challenge:

Write a program/function that can take a matrix on the form given in the top as input (directly copy/pasted from this post), and output the same matrix on all of the three other conventional formats shown below.

### The input format:

Numbers separated by a varying number of spaces, and newlines to represent rows (see test cases).

• The number of spaces between numbers are not guaranteed to be consistent. You may however assume that the last digit in each column align (if that helps any).
• There can be both integers and floats, and they can be positive, negative or zero. A matrix will not contain integers and floats at the same time.
• You may assume that no number is longer than 10 characters, including the minus and decimal point for negative floats.
• You may assume that there are the same number of entries in each row and in each column.
• There won't be any empty input matrices, but there can be single numbers, or matrices with only one row or column.
• You may in these cases choose between the output formats shown in the test cases

Your program/function must handle the input if it's directly copied from this post and pasted into the interpreter (STDIN or as function argument or something equivalent). You may have whatever you like (brackets, quotation marks, parentheses) in front of, and/or after the matrix, but you must consider the matrix a sequence of characters that can't be altered (that includes the newlines).

To clarify: Assume your function/program is called f and the matrix is:

1 -2
3  5
6  7


then you may give the matrix as function arguments like this (and infinitely many other options):

f(1 -2
3  5
6  7)

f([1 -2
3  5
6  7])

f("""1 -2
3  5
6  7""")


If your language can't, in any way, take the copy/pasted matrix as input then I'm afraid you have to pick another language.

### The output format:

You should output the matrix on the following three formats (order doesn't matter):

[[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
{{16, 2, 3, 13}, {5, 11, 10, 8}, {9, 7, 6, 12}, {4, 14, 15, 1}}
[16, 2, 3, 13; 5, 11, 10, 8; 9, 7, 6, 12; 4, 14, 15, 1]

• You may separate the three outputs however you want (e.g. a newline)
• You must output the numbers using the same precision as the input (for instance, you must not trim the number of decimals, nor output integers as floats).
• The spaces are mandatory
• You must use - for negative numbers, not _ or similar.

### Test cases:

16    2    3   13
5   11   10    8
9    7    6   12
4   14   15    1
----
[[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
{{16, 2, 3, 13}, {5, 11, 10, 8}, {9, 7, 6, 12}, {4, 14, 15, 1}}
[16, 2, 3, 13; 5, 11, 10, 8; 9, 7, 6, 12; 4, 14, 15, 1]


0.14778   0.27114   0.24415
0.45997   0.12287   0.67470
0.28945   0.37928   0.51887
----
[[0.14778, 0.27114, 0.24415], [0.45997, 0.12287, 0.6747], [0.28945, 0.37928, 0.51887]]
{{0.14778, 0.27114, 0.24415}, {0.45997, 0.12287, 0.6747}, {0.28945, 0.37928, 0.51887}}
[0.14778, 0.27114, 0.24415; 0.45997, 0.12287, 0.6747; 0.28945, 0.37928, 0.51887]


-0.0398301   0.2403455  -0.2253368   0.3565870   0.0605803   0.0830780
-0.3254422  -0.1185191  -0.2989537   0.1647319   0.3621135   0.2018815
-0.0022281  -0.3362287  -0.3568447   0.4419063   0.3801872  -0.2847033
---
[[-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780], [-0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815], [-0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033],]
{{-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780}, {-0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815}, {-0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033},}
[-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780; -0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815; -0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033]


0       4       1       0
0       0      -6       0
0       1       4      -3
2       0       0       8
0       0       0       0
----
[[0, 4, 1, 0], [0, 0, -6, 0], [0, 1, 4, -3], [2, 0, 0, 8], [0, 0, 0, 0]]
{{0, 4, 1, 0}, {0, 0, -6, 0}, {0, 1, 4, -3}, {2, 0, 0, 8}, {0, 0, 0, 0}}
[0, 4, 1, 0; 0, 0, -6, 0; 0, 1, 4, -3; 2, 0, 0, 8; 0, 0, 0, 0]


1
----
[1]     (or [[1]])
{1}     (or {{1}})
[1]     (or 1)


1 2
----
[1, 2]  (or [[1, 2]])
{1, 2}  (or {{1, 2}})
[1, 2]


4
5
----
[[4], [5]]
{{4}, {5}}
[4; 5]


I'm fully aware of this, but in this challenge, the cumbersome I/O format is the whole point. The challenge will be all about formatting the output in some languages, while reading the input will be the hardest part in other languages.

Please do not be discouraged if reading the input is hard, those submissions might be the most interesting ones. Short isn't necessarily the same as impressive. And as always, explanations are encouraged!

# Retina, 52 bytes

This answer is based on my Perl answer, with the help of Martin Ender for the golfing with Retina.

^ *
[
$] \s+ , m):.+ [$&]
*T[]{}
], .
;
^.|]$ Try it online! The explanations can be found on my Perl answer. The differences are: * [$
]


Instead of s/^ *(.+)/[$1]/gm to both remove the leading spaces and add brackets around the lines. ^.|]$


To remove the leading and trailing brackets for the third output.

## Retina, 57 54 bytes

Byte count assumes ISO 8859-1 encoding.

m^ +

¶
] [
+
,
:.+
[[$&]] *T[]{} ], . ; ^.|]$



Try it online!

The TIO link currently prints no linefeeds between the three formats but that's because it uses an unstable commit. The program does print the intermediate linefeeds in Retina 0.8.2.

### Explanation

m^ +



Get rid of leading spaces on each line.

¶
] [


Replace linefeeds with ] [.

 +
,


Replace all runs of spaces with a comma and a space.

:.+
[[$&]]  Wrap the entire thing in [[...]] which completes the first format. Print the result. *T[]{}  Replace brackets with braces and print the result without actually changing the working string (i.e. the first format is restored after this is printed). ], . ;  Replace ], [ with a semicolon and a linefeed. ^.|]$



Remove the first [ and the last ]. This completes the third format.

Try it online!

{".y/[]/{}/r."}
".s/], $/; /gr  Try it online! Explanations s/^ *(.+)/[1]/gm; adds [] around each line while removing the leading spaces. s/\s+/, /g; replaces runs of spaces and newlines with a comma and a space. The first output is then obtained by surrounding with braces: [_]. The second needs to replace braces with curly bracket (y/[]/{}/r) and surround with curly brackets "{" ... "}". For the third, ], [ are replaces with a semicolon and a space (s/], $$/; /gr). After writing this solution, I tried adpating Martin Ender's Retina answer, but it ended up 10 bytes longer (TryItOnline): s/^ +//gm;s/ /] [/g;s/ +/, /g;_="[[_]] {{".y/[]/{}/r."}} [".s/], \[/; /gr."]"  For this version, see Martin's answer for the explanations. # MATL, 60 bytes jtU&D32', 'XHYXw]xXhH&Zc91wh93htD[]&D{}&DXED&GxvUH&4'; 'TD  Try it online! Thanks a lot to Luis Mendo for shaving off a quarter of my bytecount in a masterclass in chat. Paste the input, followed by an empty line. % Act I: Taking input. jt w] % Take input line by line until an empty line is encountered. U % Convert string input to numerical row array &D % Convert back to string, adding brackets and single spaces 32', 'XHYX % Add commas before the spaces. Store ', ' in clipboard H. % Act II: Nested square brackets x % Discard the tab character Xh % Concatenate all strings as cell array. H&Zc % Join all the strings together, using clipboard H as a separator 91wh93h % Wrap in square brackets (ASCII 91 and 93) tD % Display a copy of the result. % Act III: Nested curly brackets []&D{}&D % Convert empty array and cell array to string. XE % Use to substitute square for curly brackets. % Act IV: MATLAB-style input. &Gxv % Get all the input again, discard the tab, and concatenate vertically. U % Convert to numerical &4 TD % Convert to string, using row- and column separators H'; ' % Namely, clipboard H and a semicolon.  # 05AB1E, 45 44 bytes |„ ð:ðδÛ˜ð¡„, ý''KD…[ÿ]=„[]„{}‡,"], ["„; :=  Try it online! First output | # push a list of the inputs „ ð: # replace any instance of 2 spaces with 1 space ðδÛ # remove any leading spaces ˜ # flatten to a 1D list ð¡ # split on spaces „, ý # merge on ", " ''K # remove all single quotes D # duplicate for use in output 3 …[ÿ] # interpolate between square brackets = # print without popping  Second output „[]„{}‡, # translate square brackets to curly brackets and print  Third output  # the copy from the first output is used here "], ["„; : # replace "], [" with "; " = # print  # Python 2, 143 bytes import re b=re.sub def f(s):s='[['+b('\n','], [',b(' +',', ',b('\n +','\n',s)))+']]';print s,b('\[','{',b('$','}',s)),b('$$, \[','; ',s)[1:-1]


Try it online!

# Javascript (ES6), 121110 106 bytes

-15 bytes thanks to @Shaggy and @Justin

m=>[[${(a=m.split .map(x=>x.match(/\S+/g).join, )).join], [}]] {{${a.join}, {}}}
[${a.join; }]  Example code snippet: f= m=>[[${(a=m.split
.map(x=>x.match(/\S+/g).join, )).join], [}]]
{{${a.join}, {}}} [${a.join; }]
console.log(f(
1 -2
3  5
6  7
))

• Save 4 bytes by changing map(x=>x.trim().replace(/ +/g,", ")) to map(x=>x.match(/\S+/g).join, ). – Justin Mariner Jul 1 '17 at 5:43

# Python 2, 163152150 145 bytes

-5 bytes thanks to Felipe Nardi Batista who suggested the use of splats (sorry, I just need an excuse to say that word :P).

import re
a=str.replace
def f(s):r=a([re.findall('[\.\d]+',i)for i in s.split('\n')],"'",'');print r,a(a(r,*']}'),*'[{'),a(r[1:-1],'], [','; ')


Try it online!

• Ah, splats... Thanks! – totallyhuman Jun 30 '17 at 12:26

# Python 3, 184 178 174 173 169 163* 157* 153 bytes

Input/Output Format: Output with a space between the matrices and input with this function call (as shown on TIO):

g("""<paste matrix here>""")


This is the function :

def g(s,r=str.replace):a=str([[[int,float]['.'in y](y)for y in x.split()]for x in s.split('\n')]);print(a,r(r(a,*'[{'),*']}'),'['+r(a,'], [','; ')[2:-1])


Try it online!

*Saved a 6 bytes thanks to @officialaimm (from 169 to 163 bytes).

*Saved 4 bytes thanks to @FelipeNardiBatista.

Explanation to come after further golfing.

# C, 415 bytes

#import<stdio.h>
#define A(a,c,o)for(l=strlen(a)-o,k=0;c[k];)a[l+k]=c[k++];
j,k,l;main(i){char s[999],a[999]="[",b[999]="{",c[999]="[",t[]=" ";for(;fgets(s,999,stdin);){A(b,"{",0)A(a,"[",0)for(i=0;s[i];++i){j=0;for(;s[i]-32&&s[i]-10&&s[i];++i){j=1;t[0]=s[i];A(c,t,0)A(b,t,0)A(a,t,0)}if(j){A(c,", ",0)A(b,", ",0)A(a,", ",0)}}A(c,"; ",2)A(b,"}, ",2)A(a,"], ",2)}A(c,"]",2)A(b,"}",2)A(a,"]",2)puts(a);puts(b);puts(c);}


It's a monster and waaayyyy too long, but I'm done with it. Should have gone for a different approach probably.

Try it online!

# Jelly, 37 bytes

j€⁾, j⁾; ⁾[]j
ỴḲLÐf$€VµŒṘṄ“[]“{}”yṄȧÇ  A full program printing the three formats on three lines. Try it online! ### How? j€⁾, j⁾; ⁾[]j - Link 1, create the 3rd format (semicolon-style): list of lists ⁾, - literal [',', ' '] j€ - join for €ach (place ", " between the elements of each row) ⁾; - literal [';', ' '] j - join (place "; " between the rows) ⁾[] - literal ['[', ']'] j - join (surround the whole result with a pair of brackets) ỴḲLÐf$€VµŒṘṄ“[]“{}”yṄȧÇ - Main link: list of characters
Ỵ                       - split at newlines
$€ - last two links as a monad for €ach row: Ḳ - split at spaces Ðf - filter keep those for which the following is truthy: L - length (this removes all the empty lists "between" spaces) V - evaluate as jelly code (yields a list of lists of numbers) µ - monadic chain separation, call that x ŒṘ - get a Python string representation of x Ṅ - print that (the 1st format) plus a newline, and yield it “[]“{}” - literal [['[', ']'],['{', '}']] y - translate (converts all '[' to '{' and all ']' to '}') Ṅ - print that (the 2nd format) plus a newline, and yield it Ç - call the last link as a monad with argument x ȧ - logical and - implicit print of the result (the 3rd format)  # V, 41 bytes òJé;òÓ¨ä©ó«/±, yss]Y.pkÓ; /], [ Ùòcs]}f[  Try it online! ### Explanation òJé;ò Join all lines with ;  (trailing single space) Ó¨ä©ó«/±, :s/\v(\d)\s+/\1, /g yss] Surround everything with brackets (completes [x,x;x,x]) Y.pk (Y)ank, surround with brackets again, (p)aste. Adds [[x,x;x,x]] Ó; /], [ :s/; /[, ]/g (transforms to [[x,x], [x,x]]) Ù Duplicate this line ò recursively cs]} (c)hange (s)urrounding [] with {} f[ go to the next [ until there are none  # R, 132 bytes function(x,p=paste0,g=gsub)cat(z<-p('[[',g('\n','], [',y<-g('[:blank:]',', ',x)),']]'),chartr('[]','{}',z),p('[',g(' ','; ',y),']'))  Try it online! an anonymous function. Takes input like f('1 -2 3 5 6 7')  It prints them in the same order as the test cases, but with spaces as the separator. ### Explanation: It first swaps spaces with ,  and saves the result as y. Then it swaps newlines with ], [, puts [[ and ]] on either end, and saves the result of that as z. Next, chartr switches [ with { and ] with } in z. Finally, it takes y, swaps newlines with ;  and puts [ and ] on either end. Then all the results are passed in that order to cat which prints them out, all nicely formatted, and separated by a single space. Mildly ungolfed: function(x) cat( z<-paste0('[[',gsub('\n','], [',y<-gsub('[:blank:]',', ',x)),']]'), chartr('[]','{}',z), paste0('[',gsub('\n','; ',y),']'))  # Java 8 with Netbeans 8+, 209 bytes Count is 208 from the code, plus 1 bytes to run it by pressing F6. Cumbersome answer for cumbersome challenge :p interface M{static void main(String[]a){String s="";s=s.trim().replaceAll(" +",", ").replaceAll("\n(, )?","; ");System.out.println("["+s+"]\n[["+s.replace("; ","], [")+"]]\n{{"+s.replace("; ","}, {")+"}}");}}  How to use? Within Netbeans, paste this code in a file called M.java. Then copy the matrix you want to use. Then between the two consecutive characters "", press ctrl+v as required by the challenge. Now press F6! This will compile the code, run it and output the expected matrix representations. • Doesn't this need to be in all three output formats? – Giuseppe Jun 30 '17 at 14:31 • There! That's what I missed! :D Fixing that now. – Olivier Grégoire Jun 30 '17 at 14:32 • @StewieGriffin This is advantaging languages that use STDIN by default or ones that don't care about newlines, I could also say that "copy/pasting" in any major Java IDE automatically formats changes the copy/pasted newlines into visual \n, making the result what you saw. So I don't quite get it, to be frank :s – Olivier Grégoire Jun 30 '17 at 15:04 • @OlivierGrégoire I'm fully aware that this is advantaging some languages, especially those that can handle the format without any special processing. I even mention this explicitly in the challenge text. Remember that you aren't competing against Jelly, Javascript or Python, you're using Java. It has very different functionality, and can't be fairly compared to the others. I always follow the rules about avoiding cumbersome I/O formats that might give some languages an unfair advantage, but in this particular challenge, parsing the input is a large part of it. – Stewie Griffin Jul 1 '17 at 12:35 # Mathematica, 129 bytes s=StringSplit r=StringReplace Print[#,n,#~r~{"{"->"[","}"->"]"},n,#~r~{"{{"->"[","}}"->"]","}, {"->"; "}]&@ToString@s@s[#,n=" "]&  The third and fourth lines together define a pure function taking a string as input; for example, if we set f=Print...&, then the last test case would be called as: f@"4 5"  The snippet ToString@s@s[#,n=" "]  parses the input string as a matrix (of strings—we never try to interpret the entries as numerical quantities) and converts the resulting expression back to a string; this automatically generates the output format with curly braces. Then Print[#,n,#~r~{"{"->"[","}"->"]"},n,#~r~{"{{"->"[","}}"->"]","}, {"->"; "}] prints that output format and the two others, separated by newlines, by using straightforward string replacement rules. # Pip, 49 46 bytes 45 bytes of code, +1 for -r flag. g|>:sYP(RPg^w)R';kPyR'['{R']'}O'[OgRwkJ"; "']  Takes input from stdin. Try it online! ### Explanation  Preset variables used: s is " ", w is regex \s+, k is ", " g With -r flag, g is a list of lines from stdin |>:s Left-strip spaces from (elements of) g and assign back to g YP(RPg^w)R';k g^w Split (elements of) g on runs of whitespace RP Apply Pip's built-in repr, which wraps lists in [] and separates items with ; (e.g. [[1;2];[3;4]]) ( )R';k Replace the semicolons with ", " to obtain format #1 YP Print and yank into y variable PyR'['{R']'} yR'['{ In y, replace [ with { R']'} and ] with } P and print (format #2) O'[OgRwkJ"; "'] O'[ Output [ with no newline O Output with no newline: g Take g (list of lines of stdin, with leading spaces stripped) Rwk Replace runs of whitespace with ", " J"; " and join lines on "; " '] Print the final ] to complete format #3  (This explanation format feels a bit convoluted to me, so let me know if anything didn't make sense.) # SCALA, 590 bytes Was hard, but I think I'm done with it var o=s.replaceAll(" *"," ").replaceAll("\n ","\n") var z=o.split("\n") var h=z.length var k=new Array[Array[String]](h) for(i<-0 to h-1)k(i)=z(i).split(" ") var u=k.length-1 print("{") for(i<-0 to u){print("{") for(j<-0 to k(i).length-2)print(k(i)(j)+", ") print(k(i).last) print("}")} print("}[") for(i<-0 to u){print("[") for(j<-0 to k(i).length-2)print(k(i)(j)+", ") print(k(i).last) print("]")} print("][") for(i<-0 to u-1){for(j<-0 to k(i).length-2)print(k(i)(j)+", ") print(k(i).last) print("; ")} for(j<-0 to k(k.length-1).length-2)print(k(u)(j)+", ") print(k.last.last) print("]")  Quick explanation : I take input surrounded by triple quotes, then take off unrequired spaces ; split the string two times (once for lines and once for columns) ; and I print with my three routines. It might be possible defining a function to mutualize, but I don't know how. Try it online! • This is horrible. I now have to post a Scala answer. – Tamoghna Chowdhury Jul 1 '17 at 16:02 • Have an upvote for effort, though. – Tamoghna Chowdhury Jul 1 '17 at 16:03 • You might want to take a look at codegolf.stackexchange.com/a/129356/48620 to see what might be possible with Scala. Using it like one would use pre-1.5 Java is only scratching the tip of the iceberg. – Tamoghna Chowdhury Jul 2 '17 at 14:48 • Plus, your output is wrong, which makes me want to retract my upvote - there are no commas between the brackets, as dictated by the output format. – Tamoghna Chowdhury Jul 2 '17 at 15:03 • – Tamoghna Chowdhury Jul 3 '17 at 8:47 # 05AB1E, 34 bytes |εð¡õK}€ï"ÿ"Ð„[]„{}‡s¦¨"], ["„; :»  Try it online! ε...} has been replaced with vy...}) on TIO since it hasn't been pulled there yet. • @JonathanAllan Thanks, has been fixed. – Erik the Outgolfer Jun 30 '17 at 13:28 • Cool, now it just needs an explanation of how it works :) – Jonathan Allan Jun 30 '17 at 13:33 • @JonathanAllan Sorry don't have time atm... – Erik the Outgolfer Jun 30 '17 at 13:40 # C# (.NET Core), 214 bytes (s)=>{var result=Regex.Replace("[["+Regex.Replace(s.Replace("\n","], [")," +(\\d)",",$0")+"]","  +"," ").Replace("[, ","[");return\$"{result}]\n{result.Replace('[','{').Replace(']','}')}}}\n[{result.Replace("[","").Replace("],",";")}";};


Try it online!

Takes the Matrix as a string, returns the three formats as a single string separated by newlines.

• Since this answer, I've become more certain that the using statement for libraries other than the base System should be included in the bytecount. I'll leave it in its current form for now, but the statement using System.Text.RegularExpressions is required adding (by my count) 37 additional bytes. – Kamil Drakari Jul 3 '17 at 17:16

# Charcoal, 38 bytes

≔Ｅ⪪θ¶⪫Φ⪪ι λ, θＥ⪪[]{}²⪫ι⪫Ｅθ⪫ιλ, ⪫[]⪫θ;


Try it online! Note: Trailing space. Link is to verbose version of code. Charcoal has a multiline input option delimited using [""" and """]. Explanation:

   θ                Input string
⪪ ¶               Split on newlines
Ｅ                  Map over each line
ι           Current line
⪪            Split on spaces
Φ   λ         Filter out empty strings
⪫     ,        Join with , 
≔            θ      Assign resulting array to variable


This takes the input and prepares it by splitting it into lines and normalising the separators.

 ⪪[]{}²             Split []{} into substrings of length 2
Ｅ                   Map over the substrings
Ｅθ        Map over array from above
⪫ιλ     Wrap each element with the substring
⪫     ,    Join elements with , 
⪫ι           Wrap with the substring
Implicitly print each result on a separate line


This handles the [[ ... ], [ ... ]] and {{ ... }, { ... }} cases.

    θ               Array from above
⪫ ;              Join elements with ; 
⪫[]                 Wrap result with []
Implicitly print


This handles the [ ... ; ... ] case.

Before I golfed a byte off the above solution I used to have two 39-byte solutions; this is the other:

⮌Ｅ⪪[]{}[]²⪫ι⪫ＥＥ⪪θ¶⪫Φ⪪λ ν, ⎇κ⪫ιλλ⁺§;,,κ


Try it online! Note: Trailing space. Link is to verbose version of code. Explanation:

  ⪪[]{}[]²                              Split []{}[] into substrings of length 2
Ｅ                                      Map over the substrings
θ                       Input string
⪪ ¶                      Split on newlines
Ｅ                         Map over each line
λ                  Current line
⪪                   Split on spaces
Φ   ν                Filter out empty strings
⪫     ,               Join with , 
Ｅ                          Map over each line
⎇κ   λ        If outer index is zero, just use the line
⪫ιλ         Otherwise wrap the line in the substring
⪫                   ⁺§;,,κ  Join with ;  or ,  per outer index
⪫ι                            Wrap in the substring
⮌                                       Reverse the order of the results
Implicitly print each result on a separate line
`