Making Squared Words

38

4

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.

SpookyGengar

Posted 2017-07-20T21:42:24.280

Reputation: 1 617

@DJMcMayhem Yes, my apologies I had forgotten to add that. – SpookyGengar – 2017-07-20T21:47:07.827

2No worries, just double checking. Nice first challenge BTW! Welcome to the site :) – James – 2017-07-20T21:47:28.017

@SpookyGengar Would you add a test case for a one-letter input? – musicman523 – 2017-07-20T21:58:45.377

@musicman523 don't I already have one? The third example involving just the letter 'a'. – SpookyGengar – 2017-07-20T21:59:55.903

Is empty string allowed to output to STDERR? (aka can I error out for null input) – Stephen – 2017-07-20T22:01:13.407

1@SpookyGengar my bad, I'm blind apparently – musicman523 – 2017-07-20T22:01:42.843

Ooh, this gave me an idea I have forgotten a while ago. – Matthew Roh – 2017-07-21T09:36:49.257

Do you accept the input itself as a part of the output? As in - the program doesn't output the the top line? That's the design of this answer: https://codegolf.stackexchange.com/a/133927/71498 and I'm looking for confirmation before I retract my downvote.

– Coty Johnathan Saxman – 2017-07-31T05:32:28.773

Do you accept the output as a list of (meta-approved) strings that do not have newline characters? Some solutions (e.g. Haskell) are already doing things that way, but I wanted to check. – Mark S. – 2017-08-12T15:29:54.687

Answers

17

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

Neil

Posted 2017-07-20T21:42:24.280

Reputation: 95 035

Wow, jesus, I still think Charcoal was the coolest esolang idea. – Magic Octopus Urn – 2017-07-21T01:26:03.683

1

You can save two bytes if you just print the input string and reflect it downleftwards and downrightwards: θ‖B↙↘. Try it online!

– Charlie – 2017-07-21T06:14:03.863

Now that I think of it, maybe I should have used ReflectOverlap instead of ReflectButterfly to avoid flipping characters. :-) – Charlie – 2017-07-21T06:22:11.160

1This 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. – Caleb – 2017-07-22T09:59:48.363

Your answer here also works for 4 bytes.

– Oliver – 2018-11-27T19:41:31.683

10

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

Luis Mendo

Posted 2017-07-20T21:42:24.280

Reputation: 87 464

Very impressive! :) Is it possible to remove the blank line at the bottom of every output, or is that needed for functionality? – SpookyGengar – 2017-07-20T23:22:40.790

2@SpookyGengar It's a very common request to allow a single trailing newline. – Jonathan Allan – 2017-07-20T23:24:01.977

@SpookyGengar Thanks! MATL always displays a trailing newline. As Jonathan says, that's usually allowed – Luis Mendo – 2017-07-20T23:26:03.900

1@LuisMendo You learn something new everyday. :) Thanks for the submission - definitely the best so far! – SpookyGengar – 2017-07-20T23:47:10.060

6

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

Jonathan Allan

Posted 2017-07-20T21:42:24.280

Reputation: 67 804

Very cool! So far the shortest solution, but does not work with single-character inputs, and strings consisting of numbers i.e. '123'. – SpookyGengar – 2017-07-20T22:15:59.227

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). – Jonathan Allan – 2017-07-20T22:22:34.797

@SpookyGengar - fixed it up for the 1-character case. – Jonathan Allan – 2017-07-20T22:27:17.813

Nice length reduction! – Luis Mendo – 2017-07-21T00:18:40.977

2You're right about Charcoal. – Neil – 2017-07-21T00:22:11.340

@LuisMendo thanks, three different approaches used rather than just plain glfng. – Jonathan Allan – 2017-07-21T00:27:25.453

@JonathanAllan Same as my answer then, haha – Luis Mendo – 2017-07-21T00:29:46.823

@LuisMendo Yeah a similar approach for sure! – Jonathan Allan – 2017-07-21T00:32:17.357

3

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!

Laikoni

Posted 2017-07-20T21:42:24.280

Reputation: 23 676

1you 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. – dianne – 2017-07-22T05:31:23.627

3

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.

Doorknob

Posted 2017-07-20T21:42:24.280

Reputation: 68 138

3

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

rahnema1

Posted 2017-07-20T21:42:24.280

Reputation: 5 435

2

Very nice answer. Btw: your code crashed the GNU Octave development branch 4.3.1 (b481a9baeb61) and is now part of the test suite :-) http://hg.savannah.gnu.org/hgweb/octave/rev/c94e9509461b

– Andy – 2017-07-24T13:09:57.570

1@Andy Thanks and welcome to codegolf! I glad if it can help improving Octave project! – rahnema1 – 2017-07-24T13:38:57.507

2

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!

Koishore Roy

Posted 2017-07-20T21:42:24.280

Reputation: 1 144

Same failure for length 1 strings that mine had. – Stephen – 2017-07-20T22:01:40.127

@StepHen fixed it and golfed further :D – Koishore Roy – 2017-07-20T22:10:41.570

2

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!

Giuseppe

Posted 2017-07-20T21:42:24.280

Reputation: 21 077

My answer to the dupe challenge is shorter -- what a difference a year can make!

– Giuseppe – 2018-11-01T14:57:56.087

2

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.

Emigna

Posted 2017-07-20T21:42:24.280

Reputation: 50 798

1

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.

totallyhuman

Posted 2017-07-20T21:42:24.280

Reputation: 15 378

Close! The output is not exactly what I am asking for. – SpookyGengar – 2017-07-20T21:54:29.430

189 bytes by moving s and s[::-1] into the join – musicman523 – 2017-07-20T21:54:33.637

This doesn't quite work for length-1 strings – musicman523 – 2017-07-20T22:02:39.970

2Just to note, all the issues have been fixed. – totallyhuman – 2017-07-20T22:39:56.927

1

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

Mic1780

Posted 2017-07-20T21:42:24.280

Reputation: 121

1

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

Uriel

Posted 2017-07-20T21:42:24.280

Reputation: 11 708

Can ⍉⊖⍉⊖ be ⌽⊖? – Zacharý – 2017-07-21T18:58:52.037

@Zacharý thanks – Uriel – 2017-07-22T19:07:54.777

1

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@#}])&

J42161217

Posted 2017-07-20T21:42:24.280

Reputation: 15 931

1

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;}

orlp

Posted 2017-07-20T21:42:24.280

Reputation: 37 067

1

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

traktor53

Posted 2017-07-20T21:42:24.280

Reputation: 299

You can save 7 bytes by making the second line \+s[i+1].padEnd(s.length-1)+v,s)+`` and by using r.join\``. – Justin Mariner – 2017-07-21T03:40:31.433

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 :-) – traktor53 – 2017-07-21T04:16:21.257

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\`:sand usingpadEnd(n). If the length is1,length-1is0` (false). – Justin Mariner – 2017-07-21T04:26:54.413

@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. – traktor53 – 2017-07-21T05:32:37.400

1padEnd is ES2017. – Neil – 2017-07-21T07:46:10.153

@Neil thanks, a new standard to read! – traktor53 – 2017-07-21T23:25:42.087

1

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

Levi

Posted 2017-07-20T21:42:24.280

Reputation: 147

1Welcome to PPCG! – Martin Ender – 2017-07-21T21:48:00.223

Welcome to the site as well! I believe that l+1 and could be rewritten as l+1and to save a byte. – Post Rock Garf Hunter – 2017-07-21T22:04:27.983

@WheatWizard edited - thanks! I was surprised that worked... – Levi – 2017-07-21T22:52:03.160

It will work except for the case of 0or, where python fails to parse because 0o is an octal prefix. – Post Rock Garf Hunter – 2017-07-21T22:54:15.743

When I run this, it doesn't seem to print the top line... https://tio.run/##FcoxCsQgEAXQPqeYLk7EwqRL8CRiEVh3Iww/gxhkT@@yr376bdeNbYweCvRphg8NWgvaIUEyTGe3TlFNj7A@2ZnmRWyP4pD4fVcCFVA98clGOE1i/YkX/f@@O594jHblHw

– Coty Johnathan Saxman – 2017-07-25T07:08:11.790

@CotyJohnathanSaxman the solution re-uses inputted word as first line (i.e. try copy-pasting into .py file and run from terminal and you'll see). You could add "p(w);" before the "l=len(..." to obtain what you're looking for. – Levi – 2017-07-27T14:12:27.927

1

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");

marcv

Posted 2017-07-20T21:42:24.280

Reputation: 111

0

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!

user72364

Posted 2017-07-20T21:42:24.280

Reputation:

but you only used p once... – Leaky Nun – 2017-07-21T07:15:54.510

True... gonna change that. – None – 2017-07-21T19:50:03.243

0

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>

edc65

Posted 2017-07-20T21:42:24.280

Reputation: 31 086

padEnd is ES2017. – Neil – 2017-07-21T07:46:06.420

@Neil thank you I'll change my heading – edc65 – 2017-07-21T07:53:28.447

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. – Neil – 2017-07-21T08:23:57.477

@Neil it should be l-~-i – edc65 – 2017-07-22T11:43:11.577

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. – Neil – 2017-07-22T13:14:27.640

0

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;
};

Grzegorz Puławski

Posted 2017-07-20T21:42:24.280

Reputation: 781

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++]. – TheLethalCoder – 2017-07-21T14:40:49.340

Initialise i with l like int l=s.Length-1,i=1;. And I think that might be it! – TheLethalCoder – 2017-07-21T14:41:38.930

@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. – Grzegorz Puławski – 2017-07-21T15:02:52.000

No worries! Ternaries sometimes are but usually come out shorter so is always worth trying them. – TheLethalCoder – 2017-07-21T15:04:02.387

0

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));}}};

Serverfrog

Posted 2017-07-20T21:42:24.280

Reputation: 245

(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. – TheLethalCoder – 2017-07-21T14:31:37.487

Thanks for pointing out ;) (not very familiar with Golfing). Will Optimize it later! – Serverfrog – 2017-07-21T14:36:12.743

0

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

abc123

Posted 2017-07-20T21:42:24.280

Reputation: 9

Are you sure this gives a correct answer? – Koishore Roy – 2017-07-21T17:24:45.073

0

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.

Neil

Posted 2017-07-20T21:42:24.280

Reputation: 95 035

0

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

Levi

Posted 2017-07-20T21:42:24.280

Reputation: 147

0

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!

officialaimm

Posted 2017-07-20T21:42:24.280

Reputation: 2 739

0

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

Mark S.

Posted 2017-07-20T21:42:24.280

Reputation: 251