# Make it explode!

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


# 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:

• Unknown; man; one thousand. Jun 25, 2017 at 17:52
• Now I'm confused Jun 26, 2017 at 14:49
• @MrGrj The command literally makes something blow up
– user69335
Jun 27, 2017 at 4:03
• +1 for the second gif "In the spirit of the challenge"! :) Jun 28, 2017 at 12:50

# 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  • You can save a byte: j00,0jµ€Z$⁺ Jun 25, 2017 at 13:58
• Oh, of course, thanks! Jun 25, 2017 at 14:01

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


Try it online!

# 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


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

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


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

# Dyalog APL, 24 bytes

4 bytes saved thanks to @ZacharyT

5 bytes saved thanks to @KritixiLithos

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


Try it online!

• You don't need parens around the 1,1,⍴⍵, do you? Jun 25, 2017 at 13:37
• I get this: {{⍵↑⍨-1 1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵} at 26 Jun 25, 2017 at 14:03
• @KritixiLithos nice use of 1 1+! Jun 25, 2017 at 14:15
• APL's array oriented, so would 1+ work? Jun 25, 2017 at 14:16
• @ZacharyT I just realised that after seeing your answer... Jun 25, 2017 at 14:17

# Octave, 41 bytes

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


Try it online!

# 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!

• You can remove w and save 2 bytes: repl.it/JBPE Jun 25, 2017 at 14:25
• Oh, you have an unneeded space after the line m+=[r,w] Jun 25, 2017 at 14:26
• Also, can you save 4 bytes by changing [j,0] to j,0 and [r,m[0] to r,m[0]? Jun 25, 2017 at 15:06
• You can save a 4 other bytes using array slices.
– nore
Jun 25, 2017 at 15:08
• You can save three bytes by converting to python2 and changing the for loop indentation to a single tab. Jun 25, 2017 at 15:28

# 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
• 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' Jun 25, 2017 at 20:02
• @WheatWizard: Thanks and thanks. Saved 17 bytes :) Jun 25, 2017 at 20:08
• 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 define e at all. Jun 25, 2017 at 20:11
• Ah, just thought of that myself! Hmm, I'll have to learn what .join and map() is first I guess. I'll be back! Jun 25, 2017 at 20:14
• You can put the definitions of z and r on the same line (with a ; between them), saving a byte of indentation.
– nore
Jun 25, 2017 at 21:00

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

## 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

• 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].
Jun 26, 2017 at 12:58
• Actually y=array(0,a) would be even shorter.
Jun 26, 2017 at 12:59
• I believe you can remove the parentheses around the indices, i.e., 2*1:a[1] because : has higher precedence than * Jun 26, 2017 at 20:41

# Mathematica, 55 bytes

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

• o={0,0} can be reduced to o=0{,} Jun 25, 2017 at 16:52

# 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! ## 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. # Perl 6, 33 bytes {map {0,|$_,0},0 xx$_,|$_,0 xx$_}  Try it online! ## 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] ]))) # Charcoal, 49 bytes Ａ⪪θ;αＡ””βＦ⁺¹×²Ｌ§α⁰Ａ⁺β⁰βＡ⁺β¶βＦα«βＡ0δＦιＡ⁺δ⁺κ⁰δ⁺δ¶»β  Try it online! The input is a single string separating the rows with a semicolon. • Modern Charcoal can do this in 24 bytes: ≔Ｅ⪪θ;⪫00⪫ι0θＦθ⟦⭆ι0ι⟧⭆⊟θ0 but even avoiding StringMap I still think this can be done in 27 bytes. – Neil Dec 2, 2017 at 13:02 • 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 Dec 2, 2017 at 13:04 # 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';}  ## 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
• 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. :) Jun 28, 2017 at 13:00

# Java 8, 183166162129 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


# Dyalog APL, 24 bytes

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


Any improvements are welcome and wanted!

# 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!

# 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!

## 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]))


# Pyth, 13 bytes

uCm+0s,R0dG2Q


Demonstration

Another 13:

uC.iL+0m0dG2Q


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

2× 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

# J, 24 bytes

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


Try it online!

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

• 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. :) Jan 27, 2020 at 11:08