Make it explode!

35

3

Take a matrix of positive integers as input, and make it explode!


The way you explode a matrix is by simply adding zeros around every element, including the outside borders.

Input/output formats are optional as always!

Test cases:

1
-----
0 0 0
0 1 0
0 0 0
--------------

1 4
5 2
-----
0 0 0 0 0
0 1 0 4 0
0 0 0 0 0
0 5 0 2 0
0 0 0 0 0
--------------

1 4 7
-----
0 0 0 0 0 0 0
0 1 0 4 0 7 0
0 0 0 0 0 0 0
--------------

6
4
2
-----
0 0 0
0 6 0
0 0 0
0 4 0
0 0 0
0 2 0
0 0 0

Stewie Griffin

Posted 2017-06-25T12:52:12.787

Reputation: 43 471

Answers

60

Operation Flashpoint scripting language, 182 bytes

f={t=_this;c=count(t select 0);e=[0];i=0;while{i<c*2}do{e=e+[0];i=i+1};m=[e];i=0;while{i<count t}do{r=+e;j=0;while{j<c}do{r set[j*2+1,(t select i)select j];j=j+1};m=m+[r,e];i=i+1};m}

Ungolfed:

f=
{
  // _this is the input matrix. Let's give it a shorter name to save bytes.
  t = _this;
  c = count (t select 0);

  // Create a row of c*2+1 zeros, where c is the number of columns in the
  // original matrix.
  e = [0];
  i = 0;
  while {i < c*2} do
  {
    e = e + [0];
    i = i + 1
  };

  m = [e]; // The exploded matrix, which starts with a row of zeros.
  i = 0;
  while {i < count t} do
  {
    // Make a copy of the row of zeros, and add to its every other column 
    // the values from the corresponding row of the original matrix.
    r = +e;
    j = 0;
    while {j < c} do
    {
      r set [j*2+1, (t select i) select j];
      j = j + 1
    };

    // Add the new row and a row of zeroes to the exploded matrix.
    m = m + [r, e];
    i = i + 1
  };

  // The last expression is returned.
  m
}

Call with:

hint format["%1\n\n%2\n\n%3\n\n%4",
    [[1]] call f,
    [[1, 4], [5, 2]] call f,
    [[1, 4, 7]] call f,
    [[6],[4],[2]] call f];

Output:

In the spirit of the challenge:

Steadybox

Posted 2017-06-25T12:52:12.787

Reputation: 15 798

6Unknown; man; one thousand. – MooseBoys – 2017-06-25T17:52:28.303

2Now I'm confused – Grajdeanu Alex. – 2017-06-26T14:49:24.677

@MrGrj The command literally makes something blow up – None – 2017-06-27T04:03:19.850

1+1 for the second gif "In the spirit of the challenge"! :) – Kevin Cruijssen – 2017-06-28T12:50:24.430

10

Jelly,  12  11 bytes

-1 byte thanks to Erik the Outgolfer (no need to use swapped arguments for a join)

j00,0jµ€Z$⁺

Try it online! Or see a test suite.

A monadic link accepting and returning lists of lists.

How?

j00,0jµ€Z$⁺ - Link: list of lists, m
          ⁺ - perform the link to the left twice in succession:
         $  -   last two links as a monad
      µ€    -     perform the chain to the left for €ach row in the current matrix:
j0          -       join with zeros                [a,b,...,z] -> [a,0,b,0,...,0,z]
  0,0       -       zero paired with zero = [0,0]
     j      -       join                     [a,0,b,0,...,0,z] -> [0,a,0,b,0,...,0,z,0]
        Z   -     and then transpose the resulting matrix

Jonathan Allan

Posted 2017-06-25T12:52:12.787

Reputation: 67 804

You can save a byte: j00,0jµ€Z$⁺ – Erik the Outgolfer – 2017-06-25T13:58:30.883

Oh, of course, thanks! – Jonathan Allan – 2017-06-25T14:01:16.350

7

Haskell, 38 bytes

a%l=a:(=<<)(:[a])l
f l=(0%)<$>(0<$l)%l

Try it online!

xnor

Posted 2017-06-25T12:52:12.787

Reputation: 115 687

6

MATL, 12 bytes

FTXdX*0JQt&(

Input is a matrix with ; as row separator.

Try it online!

Explanation

FT     % Push [0 1]
Xd     % Matrix with that diagonal: gives [0 0; 0 1]
X*     % Implicit input. Kronecker product
0      % Push 0
JQt    % Push 1+j (interpreted as "end+1" index) twice
&(     % Write a 0 at (end+1, end+1), extending the matrix. Implicit display

Luis Mendo

Posted 2017-06-25T12:52:12.787

Reputation: 87 464

5

Japt, 18 bytes

Ov"y ®î íZ c p0Ã"²

Test it online! (Uses the -Q flag so the output is easier to understand.)

Similar to the Jelly answer, but a whole lot longer...

Explanation

The outer part of the code is just a workaround to simulate Jelly's :

  "             "²   Repeat this string twice.
Ov                   Evaluate it as Japt.

The code itself is:

y ®   î íZ c p0Ã
y mZ{Zî íZ c p0}   Ungolfed
y                  Transpose rows and columns.
  mZ{          }   Map each row Z by this function:
     Zî              Fill Z with (no argument = zeroes).
        íZ           Pair each item in the result with the corresponding item in Z.
           c         Flatten into a single array.
             p0      Append another 0.

Repeated twice, this process gives the desired output. The result is implicitly printed.

ETHproductions

Posted 2017-06-25T12:52:12.787

Reputation: 47 880

5

Husk, 12 bytes

₁₁
Tm»o:0:;0

Takes and returns a 2D integer array. Try it online!

Explanation

Same idea as in many other answers: add zeroes to each row and transpose, twice. The row operation is implemented with a fold.

₁₁         Main function: apply first helper function twice
Tm»o:0:;0  First helper function.
 m         Map over rows:
  »         Fold over row:
   o         Composition of
      :       prepend new value and
    :0        prepend zero,
       ;0    starting from [0].
            This inserts 0s between and around elements.
T          Then transpose.

Zgarb

Posted 2017-06-25T12:52:12.787

Reputation: 39 083

5

Mathematica, 39 bytes

r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r

Try it at the Wolfram sandbox! Call it like "r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r@{{1,2},{3,4}}".

Like many other answers, this works by transposing and riffling zeros in each row then doing the same thing again. Inspired by Jonathan Allan's Jelly answer specifically, but only because I happened to see that answer first.

Not a tree

Posted 2017-06-25T12:52:12.787

Reputation: 3 106

4

Dyalog APL, 24 bytes

4 bytes saved thanks to @ZacharyT

5 bytes saved thanks to @KritixiLithos

{{⍵↑⍨-1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

Try it online!

Uriel

Posted 2017-06-25T12:52:12.787

Reputation: 11 708

You don't need parens around the 1,1,⍴⍵, do you? – Zacharý – 2017-06-25T13:37:44.887

I get this: {{⍵↑⍨-1 1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵} at 26

– user41805 – 2017-06-25T14:03:24.753

@KritixiLithos nice use of 1 1+! – Uriel – 2017-06-25T14:15:46.277

APL's array oriented, so would 1+ work? – Zacharý – 2017-06-25T14:16:47.263

@ZacharyT I just realised that after seeing your answer... – user41805 – 2017-06-25T14:17:05.190

Why did you rollback the edit? – user41805 – 2017-06-25T14:31:14.763

@KritixiLithos cos he posted an answer resembling it (with ¯1- instead of -1+) – Uriel – 2017-06-25T14:33:48.773

I'm fine if you want to use the 24 byte solution you had. – Zacharý – 2017-06-25T14:38:21.963

@ZacharyT I think any train would make a lot longer than the dfn, because of the ⍪/,/. – Uriel – 2017-06-25T15:21:00.060

Yeah, kept running into that. – Zacharý – 2017-06-25T15:22:28.857

You can just use 0⍪0, – TwiNight – 2017-06-27T01:26:57.483

3

Python 3, 104 101 97 93 86 bytes

  • @Zachary T saved 3 bytes: unused variable w removed and one unwanted space
  • @Zachary T saved yet another 4 bytes: [a,b] as just a,b while appending to a list
  • @nore saved 4 bytes: use of slicing
  • @Zachary T and @ovs helped saving 7 bytes: squeezing the statements in for loop
def f(a):
 m=[(2*len(a[0])+1)*[0]]
 for i in a:r=m[0][:];r[1::2]=i;m+=r,m[0]
 return m

Try it online!

officialaimm

Posted 2017-06-25T12:52:12.787

Reputation: 2 739

1

You can remove w and save 2 bytes: https://repl.it/JBPE

– Zacharý – 2017-06-25T14:25:40.380

1Oh, you have an unneeded space after the line m+=[r,w] – Zacharý – 2017-06-25T14:26:22.430

1Also, can you save 4 bytes by changing [j,0] to j,0 and [r,m[0] to r,m[0]? – Zacharý – 2017-06-25T15:06:16.517

1

You can save a 4 other bytes using array slices.

– nore – 2017-06-25T15:08:25.030

1You can save three bytes by converting to python2 and changing the for loop indentation to a single tab. – Zacharý – 2017-06-25T15:28:26.133

I was just about to do that. :) – officialaimm – 2017-06-25T15:28:55.740

Listen to ovs's suggestion! – Zacharý – 2017-06-25T15:30:07.820

I suggest switching to Python 2 and using print m instead of return m to save 1 byte. – Mr. Xcoder – 2017-06-25T18:26:22.570

3

Octave, 41 bytes

@(M)resize(kron(M,[0 0;0 1]),2*size(M)+1)

Try it online!

rahnema1

Posted 2017-06-25T12:52:12.787

Reputation: 5 435

3

Python 3, 118 bytes

def a(b):
    z='00'*len(b[0])+'0'
    r=z+'\n'
    for c in b:
        e='0'
        for d in c:e+=str(d)+'0'
        r+=e+'\n'+z+'\n'
    return r

First time golfing! Not the best, but I'm quite proud if I can say so myself!

  • -17 bytes from Wheat comments
  • -4 bytes from inlining the second for loop

Liren

Posted 2017-06-25T12:52:12.787

Reputation: 139

Hello and welcome to the site. You seem to have a good deal of whitespace here. For instance some of your += and = are surrounded by spaces, which can be removed. In addition doing += twice in a row could be simplified into a single statement, for example e+=str(d)+'0' – Post Rock Garf Hunter – 2017-06-25T20:02:01.117

@WheatWizard: Thanks and thanks. Saved 17 bytes :) – Liren – 2017-06-25T20:08:02.733

I'm now noticing that you can collapse your inner for loop onto a single line for d in c:e+=str(d)+'0', but you might want to go with a join map(str,d))+'0', in which case it becomes pointless to definee` at all. – Post Rock Garf Hunter – 2017-06-25T20:11:19.140

Since my last comment may have been a bit all over the place Here is the golf I had in mind

– Post Rock Garf Hunter – 2017-06-25T20:14:22.527

1Ah, just thought of that myself! Hmm, I'll have to learn what .join and map() is first I guess. I'll be back! – Liren – 2017-06-25T20:14:35.930

join is a very useful tool to know for python golfing, map is a little less useful because it can often be replaced with a list comprehension in less bytes. – Post Rock Garf Hunter – 2017-06-25T20:15:35.560

1You can put the definitions of z and r on the same line (with a ; between them), saving a byte of indentation. – nore – 2017-06-25T21:00:34.347

3

R, 65 bytes

Thanks to Jarko Dubbeldam and Giuseppe for very valuable comments!

Code

f=function(x){a=dim(x);y=array(0,2*a+1);y[2*1:a[1],2*1:a[2]]=x;y}

Input for the function must be a matrix or two dimensional array.

Test

f(matrix(1))
f(matrix(c(1,5,4,2),2))
f(matrix(c(1,4,7),1))
f(matrix(c(6,4,2)))

Output

> f(matrix(1))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    1    0
[3,]    0    0    0
> f(matrix(c(1,5,4,2),2))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    1    0    4    0
[3,]    0    0    0    0    0
[4,]    0    5    0    2    0
[5,]    0    0    0    0    0
> f(matrix(c(1,4,7),1))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    0    0    0    0    0
[2,]    0    1    0    4    0    7    0
[3,]    0    0    0    0    0    0    0
> f(matrix(c(6,4,2)))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    6    0
[3,]    0    0    0
[4,]    0    4    0
[5,]    0    0    0
[6,]    0    2    0
[7,]    0    0    0

djhurio

Posted 2017-06-25T12:52:12.787

Reputation: 1 113

At a glance I think using a=dim(x)*2+1 instead of nrow and ncol would be better. You could then do y=matrix(0);dim(y)=a and 2*1:a[1],2*1:a[2]. – JAD – 2017-06-26T12:58:30.983

1Actually y=array(0,a) would be even shorter. – JAD – 2017-06-26T12:59:33.990

1I believe you can remove the parentheses around the indices, i.e., 2*1:a[1] because : has higher precedence than * – Giuseppe – 2017-06-26T20:41:15.773

3

Python 2, 64 bytes

lambda l:map(g,*map(g,*l))
g=lambda*l:sum([[x,0]for x in l],[0])

Try it online!

The function g intersperses the input between zeroes. The main function transposes the input while applying g, then does so again. Maybe there's a way to avoid the repetition in the main function.

xnor

Posted 2017-06-25T12:52:12.787

Reputation: 115 687

2

Mathematica, 55 bytes

(a=ArrayFlatten)@{o={0,0},{0,a@Map[{{#,0},o}&,#,{2}]}}&

alephalpha

Posted 2017-06-25T12:52:12.787

Reputation: 23 988

3o={0,0} can be reduced to o=0{,} – JungHwan Min – 2017-06-25T16:52:14.913

2

PHP, 98 bytes

Input as 2D array, Output as string

<?foreach($_GET as$v)echo$r=str_pad(0,(count($v)*2+1)*2-1," 0"),"
0 ".join(" 0 ",$v)." 0
";echo$r;

Try it online!

PHP, 116 bytes

Input and Output as 2D array

<?foreach($_GET as$v){$r[]=array_fill(0,count($v)*2+1,0);$r[]=str_split("0".join(0,$v)."0");}$r[]=$r[0];print_r($r);

Try it online!

Jörg Hülsermann

Posted 2017-06-25T12:52:12.787

Reputation: 13 026

2

Clojure, 91 bytes

#(for[h[(/ 2)]i(range(- h)(count %)h)](for[j(range(- h)(count(% 0))h)](get(get % i[])j 0)))

Iterates over ranges in half-steps.

NikoNyrh

Posted 2017-06-25T12:52:12.787

Reputation: 2 361

2

Perl 6, 33 bytes

{map {0,|$_,0},0 xx$_,|$_,0 xx$_}

Try it online!

Sean

Posted 2017-06-25T12:52:12.787

Reputation: 4 136

2

JavaScript (ES6), 73 72 bytes

a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g)

Formatted and commented

Inserting zeros horizontally and vertically are very similar operations. The idea here is to use the same function g() for both steps.

a =>                            // a = input array
  (g = a =>                     // g = function that takes an array 'a',
    (                           //     builds a new array 'r' where
      r = [b],                  //     'b' is inserted at the beginning
      a.map(v => r.push(v, b)), //     and every two positions,
      b = 0,                    //     sets b = 0 for the next calls
      r                         //     and returns this new array
  ))(a, b = a[0].map(_ => 0))   // we first call 'g' on 'a' with b = row of zeros
  .map(g)                       // we then call 'g' on each row of the new array with b = 0

Test cases

let f =

a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g)

console.log(JSON.stringify(f([
  [1]
])))

console.log(JSON.stringify(f([
  [1, 4],
  [5, 2]
])))

console.log(JSON.stringify(f([
  [1, 4, 7]
])))

console.log(JSON.stringify(f([
  [6],
  [4],
  [2]
])))

Arnauld

Posted 2017-06-25T12:52:12.787

Reputation: 111 334

2

Java 8, 183 166 162 129 119 bytes

m->{int a=m.length,b=m[0].length,i=a*b,r[][]=new int[a-~a][b-~b];for(;i-->0;)r[i/b*2+1][i%b*2+1]=m[i/b][i%b];return r;}

Input and output as a int[][].

-33 bytes by creating a port of @auhmaan's C# answer.
-10 bytes thanks to @ceilingcat.

Explanation:

Try it here.

m->{                             // Method with integer-matrix as both parameter & return
  int a=m.length,                //  Set `a` to the input-height
      b=m[0].length,             //  Set `b` to the input-width
      i=a*b,                     //  Index integer, starting at `a*b`
      r[][]=new int[a-~a][b-~b]; //  Result integer-matrix with dimensions a*a+1 by b*b+1
  for(;i-->0;)                   //  Loop `i` in the range (a*b, 0] (so over each cell):
    r[i/b*2+1][i%b*2+1]=         //   Fill the current cell of the result-matrix:
      m[i/b][i%b];               //    With the correct input-integers
  return r;}                     //  Return result integer-matrix

Kevin Cruijssen

Posted 2017-06-25T12:52:12.787

Reputation: 67 575

2

Charcoal, 49 bytes

A⪪θ;αA””βF⁺¹×²L§α⁰A⁺β⁰βA⁺β¶βFα«βA0δFιA⁺δ⁺κ⁰δ⁺䶻β

Try it online!

The input is a single string separating the rows with a semicolon.

Charlie

Posted 2017-06-25T12:52:12.787

Reputation: 11 448

1Modern Charcoal can do this in 24 bytes: ≔E⪪θ;⪫00⪫ι0θFθ⟦⭆ι0ι⟧⭆⊟θ0 but even avoiding StringMap I still think this can be done in 27 bytes. – Neil – 2017-12-02T13:02:00.573

Oh, and a couple of general tips: there's a predefined variable for the empty string, and you can create a string of zeros of a given length using Times or Mold. – Neil – 2017-12-02T13:04:07.740

2

C++17 + Modules, 192 bytes

Input as rows of strings from cin, Output to cout

import std.core;int main(){using namespace std;int i;auto&x=cout;string s;while(getline(cin,s)){for(int j=i=s.length()*2+1;j--;)x<<0;x<<'\n';for(auto c:s)x<<'0'<<c;x<<"0\n";}for(;i--;)x<<'0';}

Robert Andrzejuk

Posted 2017-06-25T12:52:12.787

Reputation: 181

2

C#, 146 bytes


Data

  • Input Int32[,] m The matrix to be exploded
  • Output Int32[,] The exploded matrix

Golfed

(int[,] m)=>{int X=m.GetLength(0),Y=m.GetLength(1),x,y;var n=new int[X*2+1,Y*2+1];for(x=0;x<X;x++)for(y=0;y<Y;y++)n[x*2+1,y*2+1]=m[x,y];return n;}

Ungolfed

( int[,] m ) => {
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    return n;
}

Ungolfed readable

// Takes an matrix of Int32 objects
( int[,] m ) => {
    // To lessen the byte count, store the matrix size
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    // Create the new matrix, with the new size
    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    // Cycle through the matrix, and fill the spots
    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    // Return the exploded matrix
    return n;
}

Full code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBench {
    public static class Program {
        private static Func<Int32[,], Int32[,]> f = ( int[,] m ) => {
            int
                X = m.GetLength( 0 ),
                Y = m.GetLength( 1 ),
                x, y,

                a = X * 2 + 1,
                b = Y * 2 + 1;

            var
                n = new int[ a, b ];

            for( x = 0; x < X; x++ )
                for( y = 0; y < Y; y++ )
                    n[ a, b ] = m[ x, y ];

            return n;
        };

        public static Int32[,] Run( Int32[,] matrix ) {
            Int32[,]
                result = f( matrix );

            Console.WriteLine( "Input" );
            PrintMatrix( matrix );

            Console.WriteLine( "Output" );
            PrintMatrix( result );

            Console.WriteLine("\n\n");

            return result;
        }

        public static void RunTests() {
            Run( new int[,] { { 1 } } );
            Run( new int[,] { { 1, 3, 5 } } );
            Run( new int[,] { { 1 }, { 3 }, { 5 } } );
            Run( new int[,] { { 1, 3, 5 }, { 1, 3, 5 }, { 1, 3, 5 } } );
        }

        static void Main( string[] args ) {
            RunTests();

            Console.ReadLine();
        }

        public static void PrintMatrix<TSource>( TSource[,] array ) {
            PrintMatrix( array, o => o.ToString() );
        }
        public static void PrintMatrix<TSource>( TSource[,] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 xIndex = 0; xIndex < array.GetLength( 0 ); xIndex++ ) {
                List<String>
                    inner = new List<String>();

                for( Int32 yIndex = 0; yIndex < array.GetLength( 1 ); yIndex++ ) {
                    inner.Add( valueFetcher( array[ xIndex, yIndex ] ) );
                }

                output.Add( $"[ {String.Join( ", ", inner )} ]" );
            }

            Console.WriteLine( $"[\n   {String.Join( ",\n   ", output )}\n]" );
        }
    }
}

Releases

  • v1.0 - 146 bytes - Initial solution.

Notes

  • None

auhmaan

Posted 2017-06-25T12:52:12.787

Reputation: 906

You won't need the (int[,] m)=>, just m=> is enough if you state m is a 2D int-array int your answer. Also, you can change ,x, to ,x=0, and get rid of the x=0 in the for-loop initialization for -1 byte. And you can remove y++ from the inner loop by changing =m[x,y]; to =m[x,y++]; for an additional -1 byte. But +1 from me, and if I create a port of your answer it's also shorter than my current Java answer. :) – Kevin Cruijssen – 2017-06-28T13:00:55.660

1

Dyalog APL, 24 bytes

{{⍵↑⍨¯1-⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

Any improvements are welcome and wanted!

Zacharý

Posted 2017-06-25T12:52:12.787

Reputation: 5 710

1

Python 2, 92 bytes

n=input()
a=[[0]*(2*len(n[0])+1)for i in[0]+2*n]
for l,v in zip(a[1::2],n):l[1::2]=v
print a

Try it online!

ovs

Posted 2017-06-25T12:52:12.787

Reputation: 21 408

1

JavaScript (ES6), 80 78 bytes

a=>[...a,...a,a[0]].map((b,i)=>[...b,...b,0].map((_,j)=>i&j&1&&a[i>>1][j>>1]))

Neil

Posted 2017-06-25T12:52:12.787

Reputation: 95 035

1

Python 3 + Numpy, 87 bytes

from numpy import*
def f(a):b=zeros((2*len(a)+1,2*len(a[0])+1));b[1::2,1::2]=a;return b

Try it online!

Leaky Nun

Posted 2017-06-25T12:52:12.787

Reputation: 45 011

1

Pyth, 13 bytes

uCm+0s,R0dG2Q

Demonstration

Another 13:

uC.iL+0m0dG2Q

isaacg

Posted 2017-06-25T12:52:12.787

Reputation: 39 268

1

APL (Dyalog), 22 bytes

Prompts for matrix, returns enclosed matrix.

{⍺⍀⍵\a}/⍴∘0 1¨1+2×⍴a←⎕

Try it online!

a←⎕ prompt for matrix and assign to a

 the dimensions of a (rows, columns)

 multiply by two

1+ add one

⍴∘0 1¨ use each to reshape (cyclically) the numbers zero and one

{}/ reduce by inserting the following anonymous function between the two numbers:

⍵\a expand* the columns of a according to the right argument

⍺⍀a expand* the rows of that according to the left argument

* 0 inserts a column/row of zeros, 1 inserts an original data column/row

Adám

Posted 2017-06-25T12:52:12.787

Reputation: 37 779

0

J, 24 bytes

0,.0,[:,./^:2(0,.~,&0)"0

Try it online!

miles

Posted 2017-06-25T12:52:12.787

Reputation: 15 654

0

05AB1E, 22 bytes

"vy0ý0.ø})"©.V€Sø®.Vø»

Try it online!


Actually uses the same piece of code 2x, so I can store it as a string and use Eval for -10 bytes.

Magic Octopus Urn

Posted 2017-06-25T12:52:12.787

Reputation: 19 422

You can save some bytes by using a 2F list instead of your string with .V: 14 bytes (or 17 bytes matching your current pretty-printed output). Although I did just post an alternative 8-byter approach. :)

– Kevin Cruijssen – 2020-01-27T11:08:00.127

0

Python 2, 92 bytes

def n(a):
	l,g='0 ',len(a[0])*2+1;print l*g
	for i in a:print l+' 0 '.join(i)+' 0';print l*g

Try it online!

Koishore Roy

Posted 2017-06-25T12:52:12.787

Reputation: 1 144

0

05AB1E, 11 8 bytes

2Fε€0Ć}ø

Try it online or verify all test cases.

Explanation:

2F      # Loop 2 times:
  ε     #  Map each row of the matrix to:
        #  (which uses the (implicit) input-matrix in the first iteration)
   €0   #   Add a leading 0 before each item in the list
     Ć  #   Enclose the list, appending its own first item (to add a trailing 0 as well)
  }ø    #  After the map: zip/transpose; swapping rows/column
        # (after the loop, the result is output implicitly)

Kevin Cruijssen

Posted 2017-06-25T12:52:12.787

Reputation: 67 575