# center a matrix [closed]

The words "center a" probably give flashbacks to any decent HTML developer. Luckily, we are not working with divs, we are working with matrices.

Given a matrix where w=h, and given a "length" to extend it by, make a new matrix and center the old one in it, populating blank squares with the length. For example:

m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
l = 1

OUT = [
[1, 1, 1, 1, 1],
[1, 1, 2, 3, 1],
[1, 4, 5, 6, 1],
[1, 7, 8, 9, 1],
[1, 1, 1, 1, 1]]

m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
l = 2

OUT = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 3, 1, 1],
[1, 1, 4, 5, 6, 1, 1],
[1, 1, 7, 8, 9, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1]


I would do more examples but they are tough to type out :/

Notice that each dimension has length*2 added to it. And that the "empty" space (the new matrix) is populated with the length. Here are the parameters and rules:

Params

• vars / method can be named whatever you want
• 0 < m.length < 11
• -1 < m[x][y] < 11
• 0 < l < 11

Rules

• Input will be f(int[][] m, int l)
• Output will be int[][]
• Use the closest thing to a matrix if not available in your language
• Standard rules apply
• This is code-golf, so shortest code per language wins!

Good luck :)

• Are you sure the fill in your second example should be 1 and not 2?
May 13 at 12:49
• Please, post your future challenges to Sandbox first. May 13 at 12:54
• Isn't the second example incorrect if we should fill it with the length? EDIT: Ah, I see @Adám already mentioned this above. May 13 at 12:57
• @MarcMush I took that to mean that the input will be whole numbers, not that the actual data type would be integer. Indeed, some languages don't have integers, e.g. JavaScript.
May 13 at 13:21
• Please address the fill value confusion as pointed above, and relax I/O requirements May 13 at 23:57

# BQN, 10 bytesSBCS

Anonymous tacit infix function taking taking l as left argument and m as right argument.

∾˘⟜⌽⟜⍉⍟4⍟⊣


Run online!

⍟⊣ repeat l times:

…⍣4 repeat 4 times:

…⟜⍉ transpose, then:

…⟜⌽ flip upside-down, then:

…∾˘ concatenate l to each row of that

Alternatively:

∾˘ concatenate l to each row of…

⟜⌽ the flipped upside-down…

⟜⍉ transpose

⍟4 done four times

⍟⊣ done l times

• Just to complete the set: J port May 13 at 22:41
• @Jonah Yeah. If this gets reopened, will you post that, or do you want me to?
May 14 at 23:31
• Go for it. Thanks. May 14 at 23:32

# Pyke (non-competing†), 5 bytes

VQA.X


Since the integers are guaranteed to be single digits, I/O are multi-line strings (since the challenge asks for a strict integer-matrix I/O, I've marked it as non-competing).
Takes the length as first input, and matrix-string as second.

Try it online.

Explanation:

V      # Loop the (implicit) first input amount of times:
#  (use the implicit second multi-line input-string)
Q     #  Push the first input again
A    #  Deep apply the following command:
.X  #   Surround the string with this character around it
# (after which the result is output implicitly)


# Wolfram Language (Mathematica), 15 bytes

##~ArrayPad~#2&


Try it online!

Built-in. Input [m, l].

# Python 3.8 (pre-release), 64 bytes

lambda n,l:(c:=[[l]*(l+l+len(n))]*l)+[l*[l]+e+l*[l]for e in n]+c


Try it online!

It's been a while since I posted a working answer...so feel free to suggest golfs. There are probably plenty of them... ;)

Sure enough... thanks @Jitse for -2 bytes.

# Explanation

Constructs a matrix.

First l rows: l repeated l+l+len(n) times (length of n plus the extra, twice).

Next len(n) rows: l repeated l times, plus the current row of the matrix, plus l repeated l times.

Final l rows: same as first l rows.

Then I use the walrus operator to save bytes.

# R, 55 48 bytes

f=function(m,l)"if"(l,f(t(rbind(1,m,1)),l-.5),m)


Try it online!

-7 bytes thanks to pajonk.

+6 bytes if padding with l rather than 1.

• -7 bytes May 13 at 18:37
• @pajonk that is brilliant, thanks! May 13 at 18:56

# 05AB1E, 8 7 bytes

·FøXδ.ø


First input is the length, second the matrix.

-1 byte thanks to @emanresuA.

Try it online. (Footer ]» added to pretty-print the output, feel free to remove it to see the actual matrix result.)

Explanation:

·         # Double the (implicit) input
F        # Loop that many times:
ø      #  Zip/transepose the matrix; swapping rows/columns
#  (which will use the second implicit input in the first iteration)
δ    #  Map over each row:
.ø  #   Surround the row with a trailing/leading
X     #   1 (as integer, a literal 1 would add strings "1",
#      so with this the output is cleaner)
# (after which the result is output implicitly)


If the filler character should be the input-length (as the challenge spec says, but the second test case contradicts), it would still be 7 bytes by replacing the X with ¹ (first input): Try it online.

• I think the fill should be the length, not 1. (I made this mistake too by reason of the question only providing one example) May 13 at 12:55
• @ophact The second example has 1s padded as well, though.. :/ May 13 at 12:56
• But the question says "make a new matrix and center the old one in it, populating blank squares with the length." May 13 at 12:57
• @ophact Yeah, I noticed. I'll wait for OP to update before I fix it, but should be the same byte-count anyway by replacing X with ¹. May 13 at 12:59
• 7? May 14 at 2:26

# APL (Dyalog), 16 14 bytes

Anonymous infix lambda taking l as left argument and m as right argument.

{⍺⌽⍤⍉⍤,⍣4⍣⍺⊢⍵}


Try it online! (Uses Extended because TIO's plain Dyalog is outdated)

{} "dfn"; ⍺ is left argument and ⍵ is right argument.

⊢⍵ on the argument…

…⍣⍺ repeat l times:

…⍣4 repeat 4 times:

⍺⍤, prepend l, then:

⌽⍤⍉ mirror the transpose

• @ovs Yes, of course. Thank you!
May 13 at 13:01
• Yup, I was about to post that, but feel free to.
May 13 at 13:04
• No do that if you want. I've written a comment because I felt it was too similar for its own answer.
– ovs
May 13 at 13:06

f m l=let r=replicate;b=r l$r(length m)1;a=r l 1in map(\x->a++x++a)$b++m++b


# JavaScript (ES6), 71 bytes

(-6 bytes if we always fill with 1's instead)

Expects (length)(matrix).

(n,N=n)=>g=m=>n--?g([q=(m=m.map(r=>[N,...r,N]))[0].map(_=>N),...m,q]):m


Try it online!

# Vyxal, 8 bytes

d(∩ƛ¹p¹J


If it should be filled with 1s instead (like in the test cases), then swap the tiny ¹ with a full-size 1 for the same byte count.

How it works:

d(∩ƛ¹p¹J
d(         # Repeat 2*(length) times:
∩        #   Transpose
ƛ       #   For each row:
¹p     #     Prepend length
¹J   #     Append length


# Wolfram Language (Mathematica), 39 bytes

Nest[Thread@*Reverse@*Append[#],#2,4#]&


Try it online!

-15 bytes from ATT

Explanation:

Nest[ Repeat the following process

Thread@*Reverse@* Transpose and reverse (rotate clockwise) our matrix

Append[#], with the padding variable appended.

#2, Start with our original matrix

4#]& and do this four times the padding amount times.

Longer version that doesn't rotate the matrix:

# Wolfram Language (Mathematica), 98 bytes

f[m_,l_]:=Nest[{v}~Join~Append[#,v=Array[l&,a+l]]&,PadLeft[PadRight[#,a=Tr[1^m]+l,l],a+l,l]&/@m,l]


Try it online!

Wouldn't be surprised if this gets golfed significantly further than its current state (I suspect it would involve either MovingMap or just Transposing the matrix to do the sides instead of PadLeft/Right), but it works.

Explanation:

f[m_,l_]:= Create a function (because of slot collisions)

Nest[ that will repeatedly apply

{v}~Join~ prepending v to our list

Append[#,v= and appending it, where v is

Array[l&,a+l]]]& a list of the padding amount, of a size equal to a plus the padding amount.

PadLeft[ Our starting input will be padding the left of

PadRight[#,a= the right-padded version of the list, padded to length a,

Tr[1^m]+l, where a is the length of the matrix plus the padding amount,

l], using l as the element to pad with.

a+l, The left padding will be padded to length a+l,

l]& still using element l.

/@m, Do this padding to each row of our input matrix.

l] Finally, do the repeated application of the first step l times.

# Factor + combinators.extras, 51 bytes

[ dup <array> '[ [ _ 1surround ] map flip ] twice ]


Requires modern Factor for 1surround, so have a picture:

Here is a version that works on TIO for 3 more bytes:

Try it online!

## Explanation

• dup <array> Create an array of $$\l\$$ $$\l\$$s.
• [ ... ] twice Call a quotation two times.
• [ _ 1surround ] map Append and prepend a copy of the array to each row of the matrix.
• flip Transpose.

# Julia 1.0, 46 bytes

m>n=0<n ? [(a=ones(size(m,2));) m' a]>n-.5 : m


Try it online!

• can take non-square matrices
• recursive function. At each half-step, adds a column of ones to each side of the matrix
• output is with floats, +1 byte to have ints Try it online!

# Charcoal, 25 bytes

Ｆ⁴«ＦηＦθ⊞κθ≔Ｅ§η⁰Ｅ⮌η§μλη»Ｉη


Try it online! Link is to verbose version of code. Does not require the matrix to be square. Takes l as the first argument for consistency (see below). Explanation:

Ｆ⁴«


Repeat four times.

ＦηＦθ⊞κθ


Append l to each row l times. (ＦθＦη⊞λθ also works of course.)

≔Ｅ§η⁰Ｅ⮌η§μλη


Rotate the matrix.

»Ｉη


Output the matrix in Charcoal's default format (each element on its own line and rows double-spaced).

String-based version inspired by @KevinCruijssen's Pyke answer for 19 bytes:

ＮηＷＳ⊞υιＵＯ⁺⊗ηＬυθＭηηυ


Try it online! Link is to verbose version of code. Takes l as the first argument. Explanation:

Ｎη


Input l as an integer (θ still contains l as a character).

ＷＳ⊞υι


Input the matrix.

ＵＯ⁺⊗ηＬυθ


Draw an expanded matrix filled with the character l.

Ｍηηυ


Output the input matrix in the middle.

# Perl 5, 66 bytes

sub f{my$f=[1,(1)x@_];($l=pop)?f($f,(map[1,@$_,1],@_),$f,$l-1):@_}


Try it online!