20
\$\begingroup\$

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!

\$\endgroup\$
0

22 Answers 22

7
\$\begingroup\$

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.

\$\endgroup\$
0
6
\$\begingroup\$

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.

\$\endgroup\$
0
5
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Far better than the other Scala answer, well done! \$\endgroup\$
    – Mr. Xcoder
    Jul 2, 2017 at 13:03
4
\$\begingroup\$

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.
\$\endgroup\$
1
  • \$\begingroup\$ Well done. The best I could do was somewhere around 60 bytes... \$\endgroup\$ Jun 30, 2017 at 22:24
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Save 4 bytes by changing map(x=>x.trim().replace(/ +/g,", ")) to map(x=>x.match(/\S+/g).join`, `). \$\endgroup\$ Jul 1, 2017 at 5:43
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ Ah, splats... Thanks! \$\endgroup\$ Jun 30, 2017 at 12:26
1
\$\begingroup\$

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.

\$\endgroup\$
0
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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),']'))
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Doesn't this need to be in all three output formats? \$\endgroup\$
    – Giuseppe
    Jun 30, 2017 at 14:31
  • 1
    \$\begingroup\$ There! That's what I missed! :D Fixing that now. \$\endgroup\$ Jun 30, 2017 at 14:32
  • 2
    \$\begingroup\$ @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 \$\endgroup\$ Jun 30, 2017 at 15:04
  • \$\begingroup\$ @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. \$\endgroup\$ Jul 1, 2017 at 12:35
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
11
  • 2
    \$\begingroup\$ This is horrible. I now have to post a Scala answer. \$\endgroup\$ Jul 1, 2017 at 16:02
  • \$\begingroup\$ Have an upvote for effort, though. \$\endgroup\$ Jul 1, 2017 at 16:03
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Jul 2, 2017 at 14:48
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Jul 2, 2017 at 15:03
  • 1
    \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ Jul 3, 2017 at 8:47
0
\$\begingroup\$

05AB1E, 34 bytes

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

Try it online!

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

\$\endgroup\$
3
  • \$\begingroup\$ @JonathanAllan Thanks, has been fixed. \$\endgroup\$ Jun 30, 2017 at 13:28
  • \$\begingroup\$ Cool, now it just needs an explanation of how it works :) \$\endgroup\$ Jun 30, 2017 at 13:33
  • 1
    \$\begingroup\$ @JonathanAllan Sorry don't have time atm... \$\endgroup\$ Jun 30, 2017 at 13:40
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Jul 3, 2017 at 17:16
0
\$\begingroup\$

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.