Simplify matrix input!

20

2

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!

Stewie Griffin

Posted 2017-06-30T08:30:52.983

Reputation: 43 471

Answers

7

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.

Dada

Posted 2017-06-30T08:30:52.983

Reputation: 8 279

6

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.

Martin Ender

Posted 2017-06-30T08:30:52.983

Reputation: 184 808

5

Scala, 183 181 149 bytes

Try it online!

New version, using String replacements and regexes:

(x:String)=>{val d=x.replaceAll("\n *","; ").replaceAll("(?<!;) +",", ");(s"[[${d.replace("; ","], [")}]]",s"{{${d.replace("; ","}, {")}}}",s"[$d]")}

The new version has the same semantics and usage as the old version using split, map and mkString.

Old version, using split, map and mkString:

Edit: Redundant character class for space removed

(x:String)=>{val d=x.split("\n").map(_.trim.split(" +").mkString(", "));(d.map(x=>s"[$x]").mkString("[",", ","]"),d.map(x=>s"{$x}").mkString("{",", ","}"),d.mkString("[","; ","]"))}

Lambda. Execute in REPL. Accepts input as triple-quoted String parameter, returns output as a 3-tuple of the required outputs. The REPL renders tuples separated by commas, bordered by parentheses.

Explanation:

New version:

Mostly the same logic as the other regex-based answers, except for the tricky lookbehind to handle leading spaces on lines.

Old version:

We split the input matrix representation into a 2D String array, then map it to a 1D array by collapsing the inner arrays by separating the elements with ,. Finally, we just create the different outputs by collapsing the 1D arrays by using the required newline separators and boundary markers (prefixes and suffixes). It's all implemented via split (reading), map (transforming) and mkString (collapsing).

Example REPL session:

scala> val r=(x:String)=>{val d=x.split("\n").map(_.trim.split(" +").mkString(", "));(d.map(x=>s"[$x]").mkString("[",", ","]"),d.map(x=>s"{$x}").mkString("{",", ","}"),d.mkString("[","; ","]"))}

scala> r("""16    2    3   13
     |  5   11   10    8
     |  9    7    6   12
     |  4   14   15    1""")
res12: (String, String, String) = ([[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])

For the few-element edge cases, this provides the desired output.

Tamoghna Chowdhury

Posted 2017-06-30T08:30:52.983

Reputation: 373

2Far better than the other Scala answer, well done! – Mr. Xcoder – 2017-07-02T13:03:05.007

4

Japt, 63 53 bytes

This was coming in at 44 bytes before I noticed that the spacing in the output was mandatory.

·®¸f
"[[{q"],["}]]
\{\{{q"},\{"}}}
[{q';}]"r",|;"_+S

Test it


Explanation

          :Implicit input of string U
·         :Split to an array on newlines.
®         :Map over the array.
¸         :Split each element to an array on spaces.
f         :Filter to remove empty elements from the subarrays.
"[[       :Start building the output string. In Japt strings, anything enclosed in {}s will be evaluated before being added to the string.
{q"],["}  :Join the array to a string using ],[ The sub-arrays will be cast to comma separated strings in the process.
]]        :That's the first line done.
\{\{      :The start of the second line. A few bytes have to be sacrificed to esapce the {s
{q"},\{"} :Join the array to a string using },{
}}        :That's the second line done.
[         :And on to the last line.
{q';}     :This time we join the array with a semi-colon.
]"        :And that's the string completed.
r         :Except we still need to replace...
",|;"     :  All occurrences of a comma or a semi-colon with...
_+S       :  Itself and a space.
          :Implicit output of resulting string.

Shaggy

Posted 2017-06-30T08:30:52.983

Reputation: 24 623

Well done. The best I could do was somewhere around 60 bytes... – ETHproductions – 2017-06-30T22:24:38.070

3

Perl 5, 71 bytes

69 bytes of code + -p0 flags.

s/^ *(.+)/[$1]/gm;s/\s+/, /g;$_="[$_]
{".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.

Dada

Posted 2017-06-30T08:30:52.983

Reputation: 8 279

3

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.

Sanchises

Posted 2017-06-30T08:30:52.983

Reputation: 8 530

2

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

Emigna

Posted 2017-06-30T08:30:52.983

Reputation: 50 798

2

Javascript (ES6), 121 110 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`
))

Herman L

Posted 2017-06-30T08:30:52.983

Reputation: 3 611

Save 4 bytes by changing map(x=>x.trim().replace(/ +/g,", ")) to map(x=>x.match(/\S+/g).join`, `). – Justin Mariner – 2017-07-01T05:43:07.710

2

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!

musicman523

Posted 2017-06-30T08:30:52.983

Reputation: 4 472

1

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.

Mr. Xcoder

Posted 2017-06-30T08:30:52.983

Reputation: 39 774

1

Python 2, 163 152 150 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!

totallyhuman

Posted 2017-06-30T08:30:52.983

Reputation: 15 378

Ah, splats... Thanks! – totallyhuman – 2017-06-30T12:26:28.493

1

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

nmjcman101

Posted 2017-06-30T08:30:52.983

Reputation: 3 274

1

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!

Second test case | Third test case | Fourth test case | Fifth test case | Sixth test case | Seventh test case

Steadybox

Posted 2017-06-30T08:30:52.983

Reputation: 15 798

1

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!

V. Courtois

Posted 2017-06-30T08:30:52.983

Reputation: 868

2This is horrible. I now have to post a Scala answer. – Tamoghna Chowdhury – 2017-07-01T16:02:36.817

Have an upvote for effort, though. – Tamoghna Chowdhury – 2017-07-01T16:03:06.820

1

You might want to take a look at https://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 – 2017-07-02T14:48:26.570

Look into something cool called "string interpolation", and the utility methods on Seq, which Array provides. map and mkString being 2 very relevant ones for the job. – Tamoghna Chowdhury – 2017-07-02T14:51:48.337

Also, where do you get s (I'm assuming that that is your input String) from? Is this supposed to be an REPL session? Is this defined in a method? A lambda? Please clarify in your answer. You should include the lambda or method header in your code, not leave it in the TIO link, if you do not specify in your answer that you have done so. – Tamoghna Chowdhury – 2017-07-02T14:54:41.660

2Plus, 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 – 2017-07-02T15:03:07.193

Sorry for being away this weekend. I am correcting this comma issue. And about you telling "this is horrible" I'm totally new to this exercise, so I have to practice. I'll look at your link soon though ; thanks for it. – V. Courtois – 2017-07-03T06:56:51.483

In fact I'm getting it though :/ just correcting this issue make the code faaar too much bigger. I really have to found another algorithm - I think the problem lies here. I mean I'll redo it entirely. – V. Courtois – 2017-07-03T07:06:57.140

"It's horrible" is actually more of joke than it is serious, but I'd seriously suggest using a language you're more familiar with for code-golf. Optimising program character count is easier when you know all the folds where your language bends. – Tamoghna Chowdhury – 2017-07-03T08:40:33.117

:'( As I said, I'm a beginner in code-golf. I signed in to PPCG last week, and discovered a new programming world. In fact when I discovered ScaLa like three years ago, I found it superb in its syntax ; I now see (with your solution) that it is even able to do more. So that's my goal, and I won't forgive on coding with ScaLa.

– V. Courtois – 2017-07-03T08:46:11.087

1

Let us continue this discussion in chat.

– Tamoghna Chowdhury – 2017-07-03T08:47:06.297

1

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)

Jonathan Allan

Posted 2017-06-30T08:30:52.983

Reputation: 67 804

1

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),']'))

Giuseppe

Posted 2017-06-30T08:30:52.983

Reputation: 21 077

1

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.

Olivier Grégoire

Posted 2017-06-30T08:30:52.983

Reputation: 10 647

Doesn't this need to be in all three output formats? – Giuseppe – 2017-06-30T14:31:05.143

1There! That's what I missed! :D Fixing that now. – Olivier Grégoire – 2017-06-30T14:32:14.230

2@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 – 2017-06-30T15:04:51.870

@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 – 2017-07-01T12:35:59.340

1

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.

Greg Martin

Posted 2017-06-30T08:30:52.983

Reputation: 13 940

1

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.)

DLosc

Posted 2017-06-30T08:30:52.983

Reputation: 21 213

0

05AB1E, 34 bytes

|εð¡õK}€ï"ÿ"Є[]„{}‡s¦¨"], ["„; :»

Try it online!

ε...} has been replaced with vy...}) on TIO since it hasn't been pulled there yet.

Erik the Outgolfer

Posted 2017-06-30T08:30:52.983

Reputation: 38 134

@JonathanAllan Thanks, has been fixed. – Erik the Outgolfer – 2017-06-30T13:28:35.687

Cool, now it just needs an explanation of how it works :) – Jonathan Allan – 2017-06-30T13:33:54.850

1@JonathanAllan Sorry don't have time atm... – Erik the Outgolfer – 2017-06-30T13:40:29.780

0

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.

Kamil Drakari

Posted 2017-06-30T08:30:52.983

Reputation: 3 461

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 – 2017-07-03T17:16:37.480

0

Charcoal, 38 bytes

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

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
 E                  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
E                   Map over the substrings
          Eθ        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:

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

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

  ⪪[]{}[]²                              Split `[]{}[]` into substrings of length 2
 E                                      Map over the substrings
                θ                       Input string
               ⪪ ¶                      Split on newlines
              E                         Map over each line
                     λ                  Current line
                    ⪪                   Split on spaces
                   Φ   ν                Filter out empty strings
                  ⪫     ,               Join with `, `
             E                          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

Neil

Posted 2017-06-30T08:30:52.983

Reputation: 95 035