38
\$\begingroup\$

The Challenge

Your task is to create a program that takes any given string input, and outputs the input in a squared format. Empty strings should return an empty string.

Examples

Given the input:

golf

Your program should output:

golf
o  l
l  o
flog

Input:

123

Output:

123
2 2
321

Input:

a

Output:

a

Input:

Hello, world!

Output (notice the space between the , and w - the gap is not just a newline):

Hello, world!
e           d
l           l
l           r
o           o
,           w

w           ,
o           o
r           l
l           l
d           e
!dlrow ,olleH

Scoring

This is , so the shortest answer in each language wins.

\$\endgroup\$
  • \$\begingroup\$ @DJMcMayhem Yes, my apologies I had forgotten to add that. \$\endgroup\$ – SpookyGengar Jul 20 '17 at 21:47
  • 2
    \$\begingroup\$ No worries, just double checking. Nice first challenge BTW! Welcome to the site :) \$\endgroup\$ – DJMcMayhem Jul 20 '17 at 21:47
  • \$\begingroup\$ @SpookyGengar Would you add a test case for a one-letter input? \$\endgroup\$ – musicman523 Jul 20 '17 at 21:58
  • \$\begingroup\$ @musicman523 don't I already have one? The third example involving just the letter 'a'. \$\endgroup\$ – SpookyGengar Jul 20 '17 at 21:59
  • 1
    \$\begingroup\$ @SpookyGengar my bad, I'm blind apparently \$\endgroup\$ – musicman523 Jul 20 '17 at 22:01

26 Answers 26

17
\$\begingroup\$

Charcoal, 7 5 bytes

θ‖O↙↘

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @CarlosAlejo. Explanation:

θ       Print the input string, making the top row
 ‖O     Reflect with overlap...
   ↙    ... down and left, to create the left side
    ↘   ... down and right, to create the bottom and right sides

(Multiple directions to the Reflect command run consecutively rather than simultaneously.)

\$\endgroup\$
  • \$\begingroup\$ Wow, jesus, I still think Charcoal was the coolest esolang idea. \$\endgroup\$ – Magic Octopus Urn Jul 21 '17 at 1:26
  • 1
    \$\begingroup\$ You can save two bytes if you just print the input string and reflect it downleftwards and downrightwards: θ‖B↙↘. Try it online! \$\endgroup\$ – Charlie Jul 21 '17 at 6:14
  • \$\begingroup\$ Now that I think of it, maybe I should have used ReflectOverlap instead of ReflectButterfly to avoid flipping characters. :-) \$\endgroup\$ – Charlie Jul 21 '17 at 6:22
  • 1
    \$\begingroup\$ This is one of the rare cases where a golfed answer in an esoteric language is easier to read and understand than the full ungolfed versions of popular general purpose languages. \$\endgroup\$ – Caleb Jul 22 '17 at 9:59
  • \$\begingroup\$ Your answer here also works for 4 bytes. \$\endgroup\$ – Oliver Nov 27 '18 at 19:41
2
\$\begingroup\$

Python 2, 89 81 88 86 bytes

i=input();n=k=len(i)-2
print i
exec'print i[~k]+" "*n+i[k];k-=1;'*n
if~k:print i[::-1]

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Same failure for length 1 strings that mine had. \$\endgroup\$ – Stephen Jul 20 '17 at 22:01
  • \$\begingroup\$ @StepHen fixed it and golfed further :D \$\endgroup\$ – Koishore Roy Jul 20 '17 at 22:10
1
\$\begingroup\$

Python 2, 99 88 bytes

-4 bytes thanks to musicman523.

lambda s:s[1:]and[s]+[s[i]+' '*(len(s)-2)+s[~i]for i in range(1,len(s)-1)]+[s[::-1]]or s

Try it online!

Returns a list of strings.

\$\endgroup\$
  • \$\begingroup\$ Close! The output is not exactly what I am asking for. \$\endgroup\$ – SpookyGengar Jul 20 '17 at 21:54
  • 1
    \$\begingroup\$ 89 bytes by moving s and s[::-1] into the join \$\endgroup\$ – musicman523 Jul 20 '17 at 21:54
  • \$\begingroup\$ This doesn't quite work for length-1 strings \$\endgroup\$ – musicman523 Jul 20 '17 at 22:02
  • 2
    \$\begingroup\$ Just to note, all the issues have been fixed. \$\endgroup\$ – totallyhuman Jul 20 '17 at 22:39
6
\$\begingroup\$

Jelly,  29 22  17 bytes

Charcoal will trounce+d this score...

J⁶ẋa0,1¦"ṚṚ;$ṖŒḌY

A monadic link taking and returning a lists of characters; or a full program printing the result.

Try it online!

How?

J⁶ẋa0,1¦"ṚṚ;$ṖŒḌY - Link: list of characters, w     e.g. "whole"
 ⁶                - literal space character              ' '
J                 - range(length(w))                     [1,2,3,4,5]
  ẋ               - repeat                               [" ","  ","   ","    ","     "]
         Ṛ        - reverse w                            "elohw"
        "         - zip with:
       ¦          -   sparse application of:
   a              -     and (vectorises)
    0,1           -     to indexes: [0,1] (last and 1st) ["e","ll","o o","h  h","w   w"]
            $     - last two links as a monad:
          Ṛ       -   reverse                            ["w   w","h  h","o o","ll","e"]
           ;      -   concatenate                        ["w   w","h  h","o o","ll","e","e","ll","o o","h  h","w   w"]
             Ṗ    - pop (remove last entry)              ["w   w","h  h","o o","ll","e","e","ll","o o","h  h"]
              ŒḌ  - reconstruct matrix from diagonals    ["whole","h   l","o   o","l   h","elohw"]
                Y - join with newlines                   "whole\nh   l\no   o\nl   h\nelohw"
                  - if running as a full program implicit print
\$\endgroup\$
  • \$\begingroup\$ Very cool! So far the shortest solution, but does not work with single-character inputs, and strings consisting of numbers i.e. '123'. \$\endgroup\$ – SpookyGengar Jul 20 '17 at 22:15
  • \$\begingroup\$ Ah I will have to handle the single character edge case, yes. It does work with digit-character strings, the program input really should be quoted, like 'Hello', "Spooky's", "123", etc. (Python is used to interpret input). \$\endgroup\$ – Jonathan Allan Jul 20 '17 at 22:22
  • \$\begingroup\$ @SpookyGengar - fixed it up for the 1-character case. \$\endgroup\$ – Jonathan Allan Jul 20 '17 at 22:27
  • \$\begingroup\$ Nice length reduction! \$\endgroup\$ – Luis Mendo Jul 21 '17 at 0:18
  • 2
    \$\begingroup\$ You're right about Charcoal. \$\endgroup\$ – Neil Jul 21 '17 at 0:22
3
\$\begingroup\$

Haskell, 84 78 bytes

f s@(_:x)|_:y<-r x=s:[a:(y>>" ")++[b]|(a,b)<-zip x y]++[r s];f s=[s]
r=reverse

Try it online! Usage: f "test". Returns a list of lines.

Edit: -6 bytes thanks to dianne!

\$\endgroup\$
  • 1
    \$\begingroup\$ you can save a few bytes by using the pattern guard as a guard and defining a synonym for reverse; r=reverse;f s@(_:x)|_:y<-r x=s:[a:(y>>" ")++[b]|(a,b)<-zip x y]++[r s];f s=[s] is 78 bytes. \$\endgroup\$ – dianne Jul 22 '17 at 5:31
10
\$\begingroup\$

MATL, 20 16 11 bytes

otYTO6Lt&(c

Try it at MATL online!

EDIT: The code works in release 20.2.1, which predates the challenge. The link uses that release. (In 20.2.2 the code would be shorter, but it postdates the challenge).

Explanation

o     % Implicitly input a string. Convert chars to ASCII codes
t     % Duplicate
YT    % 2-input Toeplitz matrix
O     % Push 0
6L    % Push predefined literal [2, -1+1j]. When used as an index, this is
      % interpreted as 2:end-1 (indexing is 1-based)
t     % Duplicate
&(    % 4-input assignment indexing. This writes 0 at the square formed by
      % rows 2:end-1 and columns 2:end-1 
c     % Convert to char. Char 0 is shown as space. Implicitly display
\$\endgroup\$
  • \$\begingroup\$ Very impressive! :) Is it possible to remove the blank line at the bottom of every output, or is that needed for functionality? \$\endgroup\$ – SpookyGengar Jul 20 '17 at 23:22
  • 2
    \$\begingroup\$ @SpookyGengar It's a very common request to allow a single trailing newline. \$\endgroup\$ – Jonathan Allan Jul 20 '17 at 23:24
  • \$\begingroup\$ @SpookyGengar Thanks! MATL always displays a trailing newline. As Jonathan says, that's usually allowed \$\endgroup\$ – Luis Mendo Jul 20 '17 at 23:26
  • 1
    \$\begingroup\$ @LuisMendo You learn something new everyday. :) Thanks for the submission - definitely the best so far! \$\endgroup\$ – SpookyGengar Jul 20 '17 at 23:47
1
\$\begingroup\$

Swift 3, 215 199 bytes

let s=readLine()!,c=s.characters,r:[Character]=c.reversed(),b=c.count
print(s)
if b>1{for i in 0..<b-2{print("\(r.reversed()[i+1])\(String.init(repeating:" ",count:b-2))\(r[i+1])")};print(String(r))}

Try it online

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

APL, 58 bytes

{(' ',⍵)[x+(x←∘.{((c-1)=⍺⌈⍵)∨0=⍺⌊⍵}⍨r)×o⌊⌽⊖o←∘.⌈⍨r←⍳c←≢⍵]}

With ⎕IO←0.

Try it online!

How?

c←≢⍵ - length of the string

r←⍳ - range

o←∘.⌈⍨ - outer product with minimum

123
223
333

o⌊⌽⊖ - minimalize with itself turned 180o

123  ⌊  333  =  123
223  ⌊  322  =  222
333  ⌊  321  =  321

× - multiply with

x←∘....⍨r - outer product of the range with

    ((c-1)=⍺⌈⍵)∨0=⍺⌊⍵ - the frame of the matrix

111  ×  123  =  123
101  ×  222  =  202
111  ×  321  =  321

x+ - add the frame

111  +  123  =  234
101  +  202  =  303
111  +  321  =  432

(' ',⍵)[...] - get by index from the string concatenated to space

\$\endgroup\$
  • \$\begingroup\$ Can ⍉⊖⍉⊖ be ⌽⊖? \$\endgroup\$ – Zacharý Jul 21 '17 at 18:58
  • \$\begingroup\$ @Zacharý thanks \$\endgroup\$ – Uriel Jul 22 '17 at 19:07
3
\$\begingroup\$

C, 109 bytes

i,j;f(char*s){for(i=j=printf("%s\n",s)-2;1[++s];)printf("%c%*c\n",*s,i,s[j-=2]);for(;*s*~i--;)putchar(*s--);}

Try it online!

Noteworthy tricks:

  • Instead of wasting bytes on strlen, we simply grab the length of the string while simultaneously printing the first line:

    i=j=printf("%s\n",s)-2
    

    This works because printf returns the number of bytes written.

  • For the middle lines, we need to loop over the string but exclude both the first and last character. This is achieved with the condition

    1[++s]
    

    (which is shorter than (++s)[1]), which skips the first character due to the ++'s being in the condition and skips the last one by stopping when the character past the current character is '\0' (rather than stopping at '\0').

  • In the body of the first loop,

    printf("%c%*c\n",*s,i,s[j-=2])
    

    we print the current character, then the appropriate "mirrored" character (keeping track with j, which does go into the negatives, resulting in the odd situation of indexing into a string with a negative number) padded to a length of i with spaces (where i is conveniently strlen(s) - 1).

  • The reversed printing on the last line is pretty straightforward; the only trick is the *s*~i--, which is the shortest way to get i+2 iterations of the loop body (which doesn't depend on i; all i is used for is to count). The funky *s* part makes sure the loop doesn't run if *s is '\0', which happens on length-1 input.

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

Mathematica, 128 bytes

(c=Column;g=Length[x=Characters@#]-1;If[g==0,#,c@{#,c@Table[""<>{x[[i]],""<>Table[" ",g-1],x[[-i]]},{i,2,g}],StringReverse@#}])&
\$\endgroup\$
0
\$\begingroup\$

Lua, 104 bytes

print(s);for a=2,#s-1 do print(s:sub(a,a)..(" "):rep(#s-2)..s:sub(#s-a+1,#s-a+1)) end;print(s:reverse())

Try it online!

\$\endgroup\$
  • \$\begingroup\$ but you only used p once... \$\endgroup\$ – Leaky Nun Jul 21 '17 at 7:15
  • \$\begingroup\$ True... gonna change that. \$\endgroup\$ – user72364 Jul 21 '17 at 19:50
2
\$\begingroup\$

R, 113 bytes

function(s){n=length(s<-strsplit(s,'')[[1]])
m=matrix(' ',n,n)
m[n,n:1]=m[,1]=m[1,]=m[n:1,n]=s
write(m,'',n,,'')}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ My answer to the dupe challenge is shorter -- what a difference a year can make! \$\endgroup\$ – Giuseppe Nov 1 '18 at 14:57
1
\$\begingroup\$

C, 96 bytes

i,l;f(char*s){for(i=l=puts(s)-2;--i;)printf("%c%*c\n",s[l-i],l,s[i]);for(;l+1;)putchar(s[l--]);}

Bonus version (122 bytes):

x,y,i,l;f(char*s){for(i=l=puts(s)-1;++i<l*-~l;putchar(x==l?10:x%~-l*(y%~-l)?32:s[(x*y?l+l-2-x-y:x+y)%l]))x=i%-~l,y=i/-~l;}
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES8), 108 112 bytes

let f = 

s=>(n=s.length)<2?s:(r=[...s].reverse()).slice(1,-1).reduce((a,v,i)=>a+`
`+s[i+1].padEnd(n-1)+v,s)+`
`+r.join``

o.innerHTML = f("hello folks!")
<pre id="o"></pre>

Less golphed

s=>
   (n=s.length) < 2 ?    // record and check length
   s :                   // s has 0 or 1 char, else
   (r=[...s].reverse())  // reverse characters,
   .slice(1,-1)          // exclude 1st and last
   .reduce((a,v,i)=>     // append inner lines
      a +'\n' +s[i+1].padEnd(n-1) + v
    ,s)                  // to first line
    + '\n' +r.join("")   // append characters reversed

Thanks to Justin Mariner for saving lots of bytes, which then all got used up adding the zero or single character check needed to comply with the challenge. You get that :-(

\$\endgroup\$
  • \$\begingroup\$ You can save 7 bytes by making the second line `+s[i+1].padEnd(s.length-1)+v,s)+` and by using r.join``. \$\endgroup\$ – Justin Mariner Jul 21 '17 at 3:40
  • \$\begingroup\$ Thanks @JustinMariner for the tips about String.prototype.padStart and tagged template literals. I needed that to help keeping the addition of the length check to a minimum :-) \$\endgroup\$ – traktor53 Jul 21 '17 at 4:16
  • \$\begingroup\$ Your spacing is one character too short now; you can fix that and save a couple more by doing (n=s.length-1)?(r=<...>+r.join``:s and using padEnd(n). If the length is 1, length-1 is 0 (false). \$\endgroup\$ – Justin Mariner Jul 21 '17 at 4:26
  • \$\begingroup\$ @JustinMariner spacing is fixed, but I've kept the length test - as I understand it, both zero length strings and strings of one character return themselves without either carriage return or repetition of the string. \$\endgroup\$ – traktor53 Jul 21 '17 at 5:32
  • 1
    \$\begingroup\$ padEnd is ES2017. \$\endgroup\$ – Neil Jul 21 '17 at 7:46
0
\$\begingroup\$

JavaScript (ES2017), 87 bytes

s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i].padEnd(l)+c:z.join``:s).join`
`

ES6 version: 93 bytes

s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i]+' '.repeat(l-1)+c:z.join``:s).join`
`

Less golfed

s => (
  l = s.length-1,
  [...s].reverse().map( // scan string backwards
     (c, i, z) => 
     i != 0 // check if top row
     ? l-i != 0 // check if bottom row
       ? s[i].padEnd(l) + c // any middle row
       : z.join`` // bottom row: string reversed
     :s // top row: original string
  ).join`\n`
)

F=
s=>[...s].reverse(l=s.length-1).map((c,i,z)=>i?l-i?s[i].padEnd(l)+c:z.join``:s).join`
`

function update() {
  O.textContent = F(I.value)
}

update()
<input id=I value='Hello, world!' oninput='update()'>
<pre id=O></pre>

\$\endgroup\$
  • \$\begingroup\$ padEnd is ES2017. \$\endgroup\$ – Neil Jul 21 '17 at 7:46
  • \$\begingroup\$ @Neil thank you I'll change my heading \$\endgroup\$ – edc65 Jul 21 '17 at 7:53
  • \$\begingroup\$ You can save a byte on your ES6 version by using l+~i, this avoids having to subtract 1 twice instead you can subtract 2 once. \$\endgroup\$ – Neil Jul 21 '17 at 8:23
  • \$\begingroup\$ @Neil it should be l-~-i \$\endgroup\$ – edc65 Jul 22 '17 at 11:43
  • \$\begingroup\$ I was thinking of s=>[...s].reverse(l=s.length).map((c,i,z)=>i?l+~i?s[i]+' '.repeat(l-2)+c:z.join``:s).join`\n` but s=>[...s].reverse(l=s.length-2).map((c,i,z)=>i?i+~l?s[i]+' '.repeat(l)+c:z.join``:s).join`\n` also works. \$\endgroup\$ – Neil Jul 22 '17 at 13:14
2
\$\begingroup\$

05AB1E, 17 16 15 19 bytes

ÂDÂø¦¨Dgú€Ás)˜»Igi¨

Try it online!

Explanation

Example with input = golf

ÂDÂ                  # bifurcate, duplicate, bifurcate
                     # STACK: 'golf', 'flog', 'flog', 'golf'
   ø                 # zip the top 2 items
                     # STACK: 'golf', 'flog', ['fg', 'lo', 'ol', 'gf']
    ¦¨               # remove the first and last element
                     # STACK: 'golf', 'flog', ['lo', 'ol']
      Dg             # get the length of the list
                     # STACK: 'golf', 'flog', ['lo', 'ol'], 2
        ú            # prepend that many spaces to each element
                     # STACK: 'golf', 'flog', ['  lo', '  ol']
         €Á          # rotate each right
                     # STACK: 'golf', 'flog', ['o  l', 'l  o']
           s         # swap the top 2 items
                     # STACK: 'golf', ['o  l', 'l  o'], 'flog'
            )˜       # wrap in a flattened list
                     # STACK: ['golf', 'o  l', 'l  o', 'flog']
              »      # join on newline
               Igi¨  # if input is length 1, remove last char

The fix for 1-letter input was quite expensive.
I feel like a different approach might be better now.

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

C# (.NET Core), 179 161 bytes

-18 bytes thanks to TheLethalCoder

using System.Linq;
s=>{int l=s.Length-1,i=1;var d=s.Reverse().ToArray();while(i<l)s+="\n"+s[i]+new string(' ',l-1)+d[i++];if(l>1)s+="\n"+new string(d);return s;};

Try it online!

I'm not sure about the rules, if this is needed to byte count or not:

using System.Linq;

Someone please correct me about this.

Ungolfed:

s =>
{
    int l = s.Length - 1, i = 1;
    var d = s.Reverse().ToArray();
    while (i < l)
        s += "\n" + s[i] + new string(' ', l - 1) + d[i++];
    if (l > 1)
        s += "\n" + new string(d);
    return s;
};
\$\endgroup\$
  • \$\begingroup\$ Hello and welcome to PPCG! You are using Linq so you should include the using into your byte count. As you are using Linq ToCharArray() can be just ToArray(), do you really need it before the Reverse() though? As you are using String you either need to fully qualify it or include the using, however, this can be easily fixed by changing it too string. The if might be shorter as a ternary like s+=l>1?if code:"";. You can remove the i++ from the loop and post increment it at d[i++]. \$\endgroup\$ – TheLethalCoder Jul 21 '17 at 14:40
  • \$\begingroup\$ Initialise i with l like int l=s.Length-1,i=1;. And I think that might be it! \$\endgroup\$ – TheLethalCoder Jul 21 '17 at 14:41
  • \$\begingroup\$ @TheLethalCoder thank you! I added your suggestions to the code. A few notes: I totally forgot that string does in fact have IEnumerable; String instead of string was a Java residue that I still fight with, ternary was in fact exactly as long suprisingly; and after your changes I changed for(;expr;) to while(expr) since it looks nicer and is the same byte count. Thank you again. \$\endgroup\$ – Grzegorz Puławski Jul 21 '17 at 15:02
  • \$\begingroup\$ No worries! Ternaries sometimes are but usually come out shorter so is always worth trying them. \$\endgroup\$ – TheLethalCoder Jul 21 '17 at 15:04
0
\$\begingroup\$

Java, 191 bytes

(s)->{PrintStream o=System.out;int l=s.lenght();o.println(s);for(int i=0;i<l;i++){o.printf("%"+"s%"+(l-1)+"s%n",s.charAt(i),s.charAt(l-1-i));for(int i=0;i<l;i++){o.print(s.charAt(l-1-i));}}};
\$\endgroup\$
  • \$\begingroup\$ (s) can be just s. The loops with single lines inside can have their curly braces removed. You could return instead of printing if that will save you any bytes. You use int i in both loops, I can't tell if they're in different scopes but worth pointing out. Initialising like variables together usually saves bytes. for(int i=0;i<l;i++){o.print(s.charAt(l-1-i));} -> for(int i=0;i<l;){o.print(s.charAt(l-1-i++));}. You don't need the trailing semi colon. \$\endgroup\$ – TheLethalCoder Jul 21 '17 at 14:31
  • \$\begingroup\$ Thanks for pointing out ;) (not very familiar with Golfing). Will Optimize it later! \$\endgroup\$ – Serverfrog Jul 21 '17 at 14:36
0
\$\begingroup\$

Python 3, 85 bytes

Using the input for the top row :)

a=input()
b=len(a)
for i in range(b-2):print(a[1+i]+" "*(b-2)+a[-2-i])
print(a[::-1])
\$\endgroup\$
  • \$\begingroup\$ Are you sure this gives a correct answer? \$\endgroup\$ – Koishore Roy Jul 21 '17 at 17:24
0
\$\begingroup\$

Retina, 106 bytes

..+
$&¶$&
O$^`.(?=.*$)

\G.
$&$%'¶
r`.\G
¶$%`$&
+`(.+)¶¶((.*¶)*).(.*)
¶¶$1$4$2
T`p` `(?<=.¶.).*(?=.¶.)
G`.

Try it online! Explanation:

..+
$&¶$&

If there are at least two characters, duplicate the input.

O$^`.(?=.*$)

Reverse the duplicate.

\G.
$&$%'¶
r`.\G
¶$%`$&

Turn the strings into triangles. The top triangle starts with the input and removes the first character each time, while the bottom triangle starts with the first letter of the reversed input and adds a character each time.

+`(.+)¶¶((.*¶)*).(.*)
¶¶$1$4$2

Join the triangles together, overlapping so that the last character forms the / diagonal.

T`p` `(?<=.¶.).*(?=.¶.)

Change all the characters to spaces, if they are at least one character away from the end on every side.

G`.

Delete any left-over blank lines.

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

Octave, 40 bytes

@(s,t=toeplitz(s),u=t(x=2:end-1,x)=32)t;

Try it online!

It is my answer but posted after @Luis MATL answer

\$\endgroup\$
  • 2
    \$\begingroup\$ Very nice answer. Btw: your code crashed the GNU Octave development branch 4.3.1 (b481a9baeb61) and is now part of the test suite :-) hg.savannah.gnu.org/hgweb/octave/rev/c94e9509461b \$\endgroup\$ – Andy Jul 24 '17 at 13:09
  • 1
    \$\begingroup\$ @Andy Thanks and welcome to codegolf! I glad if it can help improving Octave project! \$\endgroup\$ – rahnema1 Jul 24 '17 at 13:38
1
\$\begingroup\$

Python 3, 88 bytes

w=input();p=print;l=len(w)-2
[p(w[n+1]+' '*l+w[l-n])for n in range(l)]
l+1and p(w[::-1])
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Jul 21 '17 at 21:48
  • \$\begingroup\$ Welcome to the site as well! I believe that l+1 and could be rewritten as l+1and to save a byte. \$\endgroup\$ – Sriotchilism O'Zaic Jul 21 '17 at 22:04
  • \$\begingroup\$ @WheatWizard edited - thanks! I was surprised that worked... \$\endgroup\$ – Levi Jul 21 '17 at 22:52
  • \$\begingroup\$ It will work except for the case of 0or, where python fails to parse because 0o is an octal prefix. \$\endgroup\$ – Sriotchilism O'Zaic Jul 21 '17 at 22:54
  • \$\begingroup\$ When I run this, it doesn't seem to print the top line... tio.run/##FcoxCsQgEAXQPqeYLk7EwqRL8CRiEVh3Iww/… \$\endgroup\$ – Coty Johnathan Saxman Jul 25 '17 at 7:08
0
\$\begingroup\$

Python 3, 106 bytes

A functional version...

w=input();p=print;l=len(w)-2
def f(k):p(w[k]+' '*l+w[-k-1]);l-k>0and f(k+1)
l<0 or f(1)or l<1or p(w[::-1])
\$\endgroup\$
1
\$\begingroup\$

PHP, 118 bytes

echo $s=$argv[1];$l=strlen($r=strrev($s))-1;for($i=$l-1;$l&&$i;)echo "\n".str_pad($r[$i],$l).$s[$i].(--$i?"":"\n$r");

Try it online!

echo $s = $argv[1];
$l = strlen($r = strrev($s)) - 1;

for ($i = $l - 1; $l && $i;)
    echo "\n" . str_pad($r[$i], $l) . $s[$i] . (--$i ? "" : "\n$r");
\$\endgroup\$
0
\$\begingroup\$

Python 2, 100 bytes

lambda a:'\n'.join([a]+(len(a)>1)*([a[i]+(len(a)-2)*' '+a[~i]for i in range(1,len(a)-1)]+[a[::-1]]))

Try it online!

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

Mathematica, 138 91 bytes

(b=Outer[" "&,#,#];Do[l={{1,k},{k,1}};b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,Length@#}];b)&

You can try it online with by pasting the following at the Wolfram Cloud Sandbox and clicking "evaluate cell" or hitting Shift+Enter or Numpad Enter:

(b=Outer[" "&,#,#];Do[l={{1,k},{k,1}};b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,Length@#}];b)&@{"g","o","l","f","y"}//MatrixForm
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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