36
\$\begingroup\$

Background

Celebrating the release of Dyalog APL 16.0, where the solution to this problem is {⊢⌺(≢⍵)⊢⍵}Explanation

Task

Given a printable ASCII string of odd length n, make an n × n square with the string centered horizontally, duplicated to be centered vertically, and with acrostics of the same string in each row and column. Note that all but the centered strings will be cut off to keep the square's size n × n.

Explanation of your code will be much appreciated.

Rules

  1. You may have trailing whitespace and newlines (this includes the lower-right triangle)
  2. You may return a list of strings

Example using the string ABXCD:

  • n is 5. First we draw the two centered strings, one horizontal and one vertical:

    ┌─────┐
    │  A  │
    │  B  │
    │ABXCD│
    │  C  │
    │  D  │
    └─────┘
    

    (5 × 5 bounding box added for clarity)

  • Then we place all the possible acrostics, horizontally and vertically:

           A
          AB
      ┌─────┐
      │  ABX│CD
      │ ABXC│D
      │ABXCD│
     A│BXCD │
    AB│XCD  │
      └─────┘
       CD
       D
    
  • Finally, we return only what is inside the bounding box:

      ABX
     ABXC
    ABXCD
    BXCD 
    XCD  
    

Test cases

World:

  Wor
 Worl
World
orld
rld

mississippi:

     missis
    mississ
   mississi
  mississip
 mississipp
mississippi
ississippi
ssissippi
sissippi
issippi
ssippi

Pneumonoultramicroscopicsilicovolcanoconiosis:

                      Pneumonoultramicroscopi
                     Pneumonoultramicroscopic
                    Pneumonoultramicroscopics
                   Pneumonoultramicroscopicsi
                  Pneumonoultramicroscopicsil
                 Pneumonoultramicroscopicsili
                Pneumonoultramicroscopicsilic
               Pneumonoultramicroscopicsilico
              Pneumonoultramicroscopicsilicov
             Pneumonoultramicroscopicsilicovo
            Pneumonoultramicroscopicsilicovol
           Pneumonoultramicroscopicsilicovolc
          Pneumonoultramicroscopicsilicovolca
         Pneumonoultramicroscopicsilicovolcan
        Pneumonoultramicroscopicsilicovolcano
       Pneumonoultramicroscopicsilicovolcanoc
      Pneumonoultramicroscopicsilicovolcanoco
     Pneumonoultramicroscopicsilicovolcanocon
    Pneumonoultramicroscopicsilicovolcanoconi
   Pneumonoultramicroscopicsilicovolcanoconio
  Pneumonoultramicroscopicsilicovolcanoconios
 Pneumonoultramicroscopicsilicovolcanoconiosi
Pneumonoultramicroscopicsilicovolcanoconiosis
neumonoultramicroscopicsilicovolcanoconiosis
eumonoultramicroscopicsilicovolcanoconiosis
umonoultramicroscopicsilicovolcanoconiosis
monoultramicroscopicsilicovolcanoconiosis
onoultramicroscopicsilicovolcanoconiosis
noultramicroscopicsilicovolcanoconiosis
oultramicroscopicsilicovolcanoconiosis
ultramicroscopicsilicovolcanoconiosis
ltramicroscopicsilicovolcanoconiosis
tramicroscopicsilicovolcanoconiosis
ramicroscopicsilicovolcanoconiosis
amicroscopicsilicovolcanoconiosis
microscopicsilicovolcanoconiosis
icroscopicsilicovolcanoconiosis
croscopicsilicovolcanoconiosis
roscopicsilicovolcanoconiosis
oscopicsilicovolcanoconiosis
scopicsilicovolcanoconiosis
copicsilicovolcanoconiosis
opicsilicovolcanoconiosis
picsilicovolcanoconiosis
icsilicovolcanoconiosis

Acknowledgements

Thanks to dzaima, Leaky Nun, Mr. Xcoder for everything but the very idea of this challenge.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Do the spaces-triange on the bottom right have to be included or not? \$\endgroup\$
    – flawr
    Commented Jul 3, 2017 at 14:21
  • 1
    \$\begingroup\$ @flawr OP: may \$\endgroup\$
    – Adám
    Commented Jul 3, 2017 at 15:20

29 Answers 29

10
\$\begingroup\$

Python 2, 60 bytes

n=input();l=len(n)
for i in range(l):print(l/2*' '+n)[i:l+i]

Try it online!

\$\endgroup\$
5
\$\begingroup\$

MATL, 8 bytes

nXyPGZ+c

Try it online!

Explanation

n    % Implicit input. Number of elements
Xy   % Identity matrix of that size
P    % Flip vertically
G    % Push input again
Z+   % 2D convolution, maintaining size
c    % Convert to char (char 0 is displayed as space). Implicitly display
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Who thought that I would like this answer :D \$\endgroup\$
    – flawr
    Commented Jul 3, 2017 at 13:40
  • 1
    \$\begingroup\$ @flawr Yes, who would have thought \$\endgroup\$
    – Luis Mendo
    Commented Jul 3, 2017 at 13:41
4
\$\begingroup\$

Retina, 70 59 bytes

.
$.'$* $_$.`$* ¶
(?=((....))+)(?<-1>.)+(.*?)(?<-2>.)+¶
$3¶

Try it online! Edit: Saved 11 bytes with some help from @MartinEnder. Explanation: The first stage repeats the input once for each character, padding it appropriately on each line to get the shear. The last stage then removes 25% from each side to produce the desired result.

\$\endgroup\$
5
  • \$\begingroup\$ I think I had 59 earlier. Don't have time to dig up the details now, but essentially in the first stage I just padded the input with n/2 spaces left and right (using something like (..)+. --> $#1$* $&$#1$* with a trailing space) and then just did a !&`... where ... matches n exactly n characters. \$\endgroup\$ Commented Jul 3, 2017 at 20:50
  • \$\begingroup\$ Your approach can at least be shortened to 63: tio.run/##K0otycxL/… \$\endgroup\$ Commented Jul 3, 2017 at 20:53
  • \$\begingroup\$ @MartinEnder Thanks, and I've golfed another 4 bytes off! \$\endgroup\$
    – Neil
    Commented Jul 3, 2017 at 21:23
  • \$\begingroup\$ Do you need the second $*sp? \$\endgroup\$ Commented Jul 5, 2017 at 17:50
  • \$\begingroup\$ @CalculatorFeline Yes, I need all the lines to be the same length, so I can divide it by 4. \$\endgroup\$
    – Neil
    Commented Jul 5, 2017 at 18:51
3
\$\begingroup\$

Java 8, 120 103 bytes

s->{int l=s.length(),i=l/2;for(;i-->0;s=" "+s+" ");for(;++i<l;System.out.println(s.substring(i,l+i)));}

-17 bytes thanks to @OlivierGrégoire.

Explanation:

Try it here.

s->{                      // Method with String parameter and no return-type
  int l=s.length(),       //  Length of the input-String
      i=l/2;              //  Temp index-integer (starting at halve the length floored)
  for(;i-->0;             //  Loop (1) from `l/2` to 0 (exclusive)
    s=" "+s+" "           //   Add spaces before and after the input-String
  );                      //  End of loop (1)
                          //  (If the input was "World", it is now "  World  ")
  for(;++i<l;             //  Loop (2) from 0 to `l` (exclusive)
    System.out.println(   //   Print:
      s.substring(i,      //    Substring of the modified input from `i`
                    l+i)  //    to `l+i` (exclusive)
    )                     //   End of print
  );                      //  End of loop (2)
}                         // End of method
\$\endgroup\$
2
  • \$\begingroup\$ i=l/2+1 and i-->1 and for(;i<l save a byte. \$\endgroup\$ Commented Jul 3, 2017 at 12:43
  • 1
    \$\begingroup\$ And... totally golfed: s->{int l=s.length(),i=l/2;while(i-->0)s=" "+s+" ";while(++i<l)System.out.println(s.substring(i,l+i));} (103 bytes). The only significant change is that the string with spaces is generated once and for all instead of "on the fly" (and of course the print instead of returning). \$\endgroup\$ Commented Jul 3, 2017 at 12:55
3
\$\begingroup\$

Haskell, 64 62 bytes

f s|l<-length s=take l$take l<$>scanr(:)""(([2,4..l]>>" ")++s)

Try it online! How it works:

l<-length s               -- let l be the length of the input string

      ([2,4..l]>>" ")     -- take l/2 spaces and
                     ++s  -- append s
    scanr(:)""            -- make a list of the inits of the above string, e.g.
                          -- "  world" -> ["  world"," world","world","orld"...]
  take l <$>              -- take the first l chars of each string
take l                    -- and the first l strings
\$\endgroup\$
3
\$\begingroup\$

SWI Prolog, 234 bytes

h(_,0,_,_,[]).
h(T,N,S,L,[H|U]):-sub_string(T,S,L,_,H),M is N-1,A is S+1,h(T,M,A,L,U).
s(T,R):-string_length(T,L),findall('_',between(1,L,_),A),string_chars(B,A),
                   string_concat(B,T,C),string_concat(C,B,D),S is L-((L-1)/2),h(D,L,S,L,R).

Maybe try online here: http://swish.swi-prolog.org/p/hEKigfEl.pl

NB.

  1. The last line is one long line, I added a linebreak and spaces here just to avoid horizontal scrollbar in this answer.
  2. The question involves spaces for padding, but Swish online doesn't show them cleanly because of HTML rendering interactions, you have to view source in browser dev tools to check they are present (they are). I've changed the padding to be _ here, as it demonstrates it working and doesn't affect the byte count.

Examples running in Swish:

Test cases

Approach, basically the first thing I could make work at all, and doubtless a skilled Prolog user could shorten it a lot:

  • Given a string of length L, the output will have L lines, and each line will be L characters long, so 'L' shows up a lot. Countdown from L to 0 for the number of lines, L for the substring length for each line.
  • Create a padding string of L spaces (underscores) long, add it to both ends of the input string, because that's a simple length which is definitely going to be enough padding.
  • Calculate a starting offset into this triple-length string and recurse, generating a substring each time, into a list of results.

Explained and commented code (might not run), read from superacrostic() down, then helper() main body, then helper() base case:

% helper function recursive base case, 
% matches when counter is 0, other input has any values, and empty list 'output'.
helper(_,0,_,_,[]). 



% helper function recursively generates substrings
% matching a padded input Text, a line Counter
% a substring starting Offset, a line Length,
% and an output list with a Head and a Tail
helper(Text, Counter, Offset, LineLength, [Head|Tail]):-

    sub_string(Text, Offset, LineLength, _, Head),    % The list Head matches
                                                      % a substring of Text starting 
                                                      % from Offset, of LineLength chars 
                                                      % and

    NextCounter is Counter-1,                         % decrement the Counter

    NextOffset is Offset+1,                           % increment the offset

    helper(Text, NextCounter, NextOffset, LineLength, Tail).  % Recurse for list Tail



% Result is a superacrostic for an input string Text, if
superacrostic(Text, Result):-
    string_length(Text, Length),                   % Length is length of input, 
                                                   % Text = 'ABXCD', Length = 5
                                                   % and

    findall('_',between(1,Length,_),PaddingList),  % PaddingList is a list of padding
                                                   % chars Length items long, 
                                                   % ['_', '_', '_', '_', '_']
                                                   % and

    string_chars(PaddingString, PaddingChars),     % PaddingString is the string from 
                                                   % joining up that list of chars
                                                   % '_____'
                                                   % and

    string_concat(PaddingString, Text, Temp),      % Temp is Text input with a
                                                   % padding prefix
                                                   % Temp = '_____ABXCD'
                                                   % and

    string_concat(Temp, PaddingString, PaddedText), % PaddedText is Temp with 
                                                    % a padded suffix
                                                    % Temp = '_____ABXCD_____'
                                                    % and


    S is Length - ((Length - 1) / 2),              % Starting offset S for the substring
                                                   % is just past the padding,
                                                   % then half the input length back
                                                   % '_____ABXCD_____'
                                                   %     |
                                                   % to start the first line,
                                                   % and


    helper(PaddedText, Length, S, Length, Result). % Result is the list generated from 
                                                   % the helper function, 

    % to recurse Length times for that many output rows, S starting offset, 
    % Length linelength, and Result 'output'.
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 11 bytes

g;úIvDIg£,À

Try it online!

Explanation

g;ú           # prepend len(input)/2 spaces to input
   Iv         # for each char of input do
     D        # duplicate current string
      Ig£     # take the first len(input) chars
         ,    # print
          À   # rotate the string to the left
\$\endgroup\$
0
2
\$\begingroup\$

JavaScript (ES6), 75 bytes

f=(s,k=1,l=s.length)=>k>l?'':(' '.repeat(l)+s).substr(l/2+k,l)+`
`+f(s,k+1)

console.log(f("World"))

\$\endgroup\$
1
  • \$\begingroup\$ 72 bytes. Or 70 bytes if you want to go with ES8, like I did. \$\endgroup\$
    – Shaggy
    Commented Jul 6, 2017 at 17:43
2
\$\begingroup\$

APL (Dyalog Unicode), 10 chars = 22 bytes

{⊢⌺(≢⍵)⊢⍵}

Try it online!

{} anonymous function where the argument is represented by

 provide the covered area when

⌺() sliding a stencil of size

   length of

   the argument

 on

 the argument

The way this works is by letting each character form the middle of a string with the same length as the input, padding left or right as needed. Take e.g. ABXCD:

The string has five characters, so the stencil will have an "opening" that is five characters wide.

┌──↓──┐     stencil opening with middle marker
│ ABX│CD   let A be in the middle
 │ ABXC│D   then B
  │ABXCD|   etc.
  A|BXCD | 
  AB|XCD  |
    └──↑──┘ final stencil position

\$\endgroup\$
2
\$\begingroup\$

PHP, 98 bytes

for(;~($a=$argn)[$i++];)$i&1?$t.=substr($a,$i/2)."
":$t=($s.=" ").substr($a,0,-$i/2)."
$t";echo$t;

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES8), 66 63 62 bytes

Returns an array.

s=>[...s].map((_,x)=>s.padStart(l*1.5).substr(x,l),l=s.length)

Try it

o.innerText=(f=
s=>[...s].map((_,x)=>s.padStart(l*1.5).substr(x,l),l=s.length)
)(i.value="Pneumonoultramicroscopicsilicovolcanoconiosis").join`\n`;oninput=_=>o.innerText=f(i.value).join`\n`
<input id=i><pre id=o>


Explanation

s=>

Anonymous function taking the string as an argument via parameter s.

[...s]

Split the string to an array of individual characters.

l=s.length

Get the length of the string and assign it to variable l.

.map((_,x)=>                                        )

Map over the array, passing each element through a function, where x is the index of the current element.

s.padStart(l*1.5)

For each element, return the original string with spaces prepended until it's length is 1.5 times that of it's original length.

.substr(x,l)

Get the substring of length l beginning from the current element's index.

\$\endgroup\$
2
\$\begingroup\$

V, 14, 11 bytes

òlÙxHÄ$x>>ê

Try it online!

3 bytes saved thanks to @nmjmcman!

Hexdump:

00000000: f26c d978 48c4 2478 3e3e ea              .l.xH.$x>>.

Original approach (18 bytes):

ø..
Duu@"ñLÙxHÄ$x>

Explanation:

ò           " Recursively:
 l          "   Move one char to the right (this will break the loop if we move too far
  Ù         "   Duplicate this line down
   x        "   Delete the first character on this line
    H       "   Move to the first line
     Ä      "   Duplicate this line up
      $     "   Move to the end of this line
       x    "   And delete a character
        >>  "   Put one space at the beginning of this line
          ê "   And move to this column on the last line
            " (implicit) ò, end the loop.
\$\endgroup\$
2
  • \$\begingroup\$ Save a couple of bytes: Try it online! \$\endgroup\$
    – nmjcman101
    Commented Jul 6, 2017 at 16:28
  • \$\begingroup\$ @nmjcman101 Ah, that's genius! I totally forgot about ê. Thanks :) \$\endgroup\$
    – DJMcMayhem
    Commented Jul 6, 2017 at 16:34
2
\$\begingroup\$

PowerShell Core, 68 bytes

0..($L=($a="$args").Length-1)|%{-join(' '*($L/2)+$a)[($_..($_+$L))]}

Try it online!

Ungolfed explanation

# Input string ABXCD
# -> indexes  0,1,2,3,4  string indexing and num of output lines.
# -> Pad with half-len of spaces __ABXCD.
# -> sliding window array of chars:
# __ABXCD
# |    |       0..4
#  |    |      1..5
#   |    |     2..6
#    |    |    3..7   (selecting indexes past the end returns $nulls, no error)
#     |    |   4..8

# joining those chars into a line


$Text = "$args"                            # script args array to string.
$L    = $Text.Length - 1                   # useful number

$Offsets = 0..$L                           # range array 0,1,2,3,.. to last offset

$Offsets | ForEach-Object {                # Offsets doubles as number of output lines

    $LinePadding = ' ' * ($L / 2)          # lead padding string __
    $PaddedText  = $LinePadding + $Text    # -> __ABXCD

    $Chars = $_..($_+$L)                   # windows 0..4, then 1..5, then 2..6, etc.
    $Line  = $PaddedText[$Chars]           #_,_,A,B,X then _,A,B,X,C then A,B,X,C,D etc.

    -join $Line                            # __ABX  then _ABXC then ABXCD etc.

}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Care to ungolf the join to [($_..($_+$L))]? \$\endgroup\$
    – root
    Commented Jul 6, 2017 at 20:42
  • \$\begingroup\$ @root short answer, the ( doesn't go with the join, it's doing -join ($Padding + $Text)[0,1,2,3,4] to select several characters from a padded string for an output line, and joining those into a string to be a shorter way of doing .SubString(). and it's generating the padding in-place and the range of characters in-place. Full ungolf explanation added to my answer. \$\endgroup\$ Commented Jul 7, 2017 at 18:04
2
\$\begingroup\$

Japt, 19 17 14 bytes

Saved 5 bytes thanks to @ETHproductions and @Shaggy

¬£iSp½*Ul¹tYUl

Test it online! -R flag added to join with newlines (visibility purposes)

Explanation

¬£iSp½*Ul¹tYUl
                U = Implicit input
¬               Split the input into an array of chars
 £              Map; At each char:
  i               Insert:
   S                Space " "
    p               repeated(
     ½*Ul           .5 * U.length times 
         ¹          )
          t        Substring(
           Y         Index,
            Ul       U.length) 
\$\endgroup\$
4
  • 1
    \$\begingroup\$ There should be a much shorter way to generate Sp½*Ul, but I don't think there is one atm... BTW, you can usually change sXX+Y to tXY (s == .slice, t == .substr) \$\endgroup\$ Commented Jul 3, 2017 at 21:46
  • \$\begingroup\$ @ETHproductions Oh yeah, thanks! \$\endgroup\$
    – Oliver
    Commented Jul 3, 2017 at 23:04
  • \$\begingroup\$ 16 bytes \$\endgroup\$
    – Shaggy
    Commented Jul 6, 2017 at 9:42
  • \$\begingroup\$ Or, seeing as returning a array is permitted, 14 bytes. \$\endgroup\$
    – Shaggy
    Commented Jul 6, 2017 at 9:50
1
\$\begingroup\$

Charcoal, 26 bytes

A⁺¹÷Lθ²δFδ⟦✂θι⁺ιδ⟧F∕θ²C¹±¹

Try it online! Link is to verbose version of code.

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

Jelly, 11 bytes

LH⁶ẋ;ṫJḣ€LY

Try it online!

How it works

LH⁶ẋ;ṫJḣ€LY   "ABXCD"
L             5
 H            2.5
  ⁶ẋ          "  "
    ;         "  ABXCD"
     ṫJ       ["  ABXCD"
               " ABXCD"
               "ABXCD"
               "BXCD"
               "XCD]
        ḣ€L   ["  ABX"
               " ABXC"
               "ABXCD"
               "BXCD"
               "XCD]
           Y  "  ABX
                ABXC
               ABXCD
               BXCD
               XCD"
\$\endgroup\$
1
\$\begingroup\$

QBIC, 32 bytes

_L;|A=space$(a'\`2)+A[a|?_sA,b,a    

Man, it's time for me to add space$ to QBIC...

Explanation

  ;             Read a cmd line parameter as A$
_L |            And take its length as 'a'
A=space$        Set A$ to a number of spaces
(a'\`2)           equal to its own length halved
+A                prepended to itself
[a|             FOR b= 1 to the length of A$
?_sA,b,a        Print a substring of our space-padded A$, starting at the b'th character, running for a chars

Sample run

Command line: acknowledgement
       acknowle
      acknowled
     acknowledg
    acknowledge
   acknowledgem
  acknowledgeme
 acknowledgemen
acknowledgement
cknowledgement
knowledgement
nowledgement
owledgement
wledgement
ledgement
edgement
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 88 bytes

T=Table;Column@Reverse@T[T[" ",i]<>StringDrop[s=#,-i],{i,d=-⌊StringLength@s/2⌋,-d}]&
\$\endgroup\$
1
\$\begingroup\$

Haskell, 86 70 bytes

This is (still) way too long, but thanks @bartavelle for reminding me that outputting a list of strings is acceptable too!

f s|m<-div(length s)2=take(2*m+1).(`drop`((*>)s" "++s))<$>[m+1..3*m+1]

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ I could only reach 82 : Try it online! \$\endgroup\$
    – bartavelle
    Commented Jul 3, 2017 at 16:14
  • \$\begingroup\$ @bartavelle That doesn't look right. Your right side isn't chopped. \$\endgroup\$
    – Adám
    Commented Jul 3, 2017 at 16:26
  • \$\begingroup\$ Yep I introduced a bug! You can gain a bit by dropping your concat : Try it online! \$\endgroup\$
    – bartavelle
    Commented Jul 3, 2017 at 16:28
  • \$\begingroup\$ And with the chopping it's 84, making your approach better! Try it online! \$\endgroup\$
    – bartavelle
    Commented Jul 3, 2017 at 16:29
  • \$\begingroup\$ And you can save a lot more, because you don't need to return a single string, lists of strings are OK too! \$\endgroup\$
    – bartavelle
    Commented Jul 3, 2017 at 16:32
1
\$\begingroup\$

Excel VBA, 68 Bytes

Golfed

Anonymous VBE immediate window function that takes input from cell [A1] and outputs to the VBE immediate window

l=[Len(A1)]:For i=Int(-l/2)+2To l/2+1:?Mid(Space(l-i)&[A1],l,l):Next

Ungolfed

Sub C(ByVal s As String)
    Let l = Len(s)
    For i = Int(-l / 2) + 2 To l / 2 + 1 Step 1
        Debug.Print Mid(Space(l - i) & s, l, l)
    Next i
End Sub
\$\endgroup\$
1
  • 1
    \$\begingroup\$ With the added functions in Excel since this question was posted, it's now shorter without VBA. This one is 64 bytes and basically implements your solution in a formula: =LET(L,LEN(A1),MID(REPT(" ",L-SEQUENCE(L,,INT(-L/2)+2))&A1,L,L)) \$\endgroup\$ Commented Oct 24, 2022 at 16:35
1
\$\begingroup\$

Python 3, 68 bytes

a=input()
c=len(a)
b=a.center(c*2)
for i in range(c):print(b[i:i+c])

Try it online!

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

PowerShell, 133 119 bytes

$a="$args";$L=$a.Length;$m=($L+1)/2;$s=" "*($m-1)+$a+" "*($m-1);for($h=0;$h-lt$L;$h++){$r="";0..$L|%{$r+=$s[$_+$h]};$r}

Try it online!

Ungolfed

$a="$args"
$L=$a.Length                        # the length of the input
$m=($L + 1) / 2                     # the midpoint of the input
$s=" " * ($m-1) + $a + " " * ($m-1) # create a string using the input and padded on both sides with spaces

for($h=0;$h -lt $L;$h++) {          # the height, matching the length of the input
    $r=""                           # init/reset the output string

    0..$L | % {                     # number range to represent each character in the string
        $r+=$s[$_+$h]               # append the output string with the next character
    }

    $r                              # write the output
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice answer! Welcome to the site. :) \$\endgroup\$
    – DJMcMayhem
    Commented Jul 7, 2017 at 18:51
1
\$\begingroup\$

Python 2, 76 74 73 bytes

-1 thanks to @FelipeNardiBatista

Of course, not as short as the other Python answer, but it's worth trying a completely different method:

n=input();x=len(n)
for i in range(x):print((2*x-~i)*' '+n)[x+x/2:2*x+x/2]

Try it online! (with the 74 byte version)

This first generates the full String, and then slices it to fit the square.


Explanation

n=input();                                                  - takes input and assigns it to a variable n
          x=len(n)                                          - assigns the length of the input to a variable x
for i in range(x):                                          - iterates on the range 0...x, with a variable i
                   print                                    - outputs the result
                         ((2*x-i-1)*' '+n)                  - creates the "diamond" string
                                          [x+x/2:2*x+x/2]   - crops the string to fit the box
\$\endgroup\$
2
  • \$\begingroup\$ (2*x+~i) to save a byte \$\endgroup\$ Commented Jul 4, 2017 at 13:18
  • \$\begingroup\$ @FelipeNardiBatista Thanks. \$\endgroup\$
    – user70974
    Commented Jul 10, 2017 at 11:02
1
\$\begingroup\$

J, 19 bytes

|.!.' '"{~2%~#\-#\.

Try it online!

Explanation

|.!.' '"{~2%~#\-#\.  Input: string S
             #\      Length of each prefix of S, [1, 2, ..., len(S)]
                #\.  Length of each suffix of S, [len(s), ..., 2, 1]
               -     Subtract elementwise
          2%~        Divide by 2
                     We now have a range [(1-len(S))/2, ..., -1, 0, 1, ..., (len(S)-1)/2]
       "{~           Use each value to operate on S
|.!.' '                Perform a shift while replacing characters with ' '
\$\endgroup\$
1
  • \$\begingroup\$ Works with '' as the replacement. \$\endgroup\$
    – FrownyFrog
    Commented Jan 11, 2018 at 16:17
1
\$\begingroup\$

Perl 5, 53 + 1 (-n) = 54 bytes

$t=$"x(($\=y%%%c)/2).$_;say substr$t,$_,$\for 0..$\-1

Try it online!

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

Ruby -nl, 44 bytes

puts (0...c= ~/$/).map{$_.center(c*2)[_1,c]}

Attempt This Online!

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

Japt -R, 11 bytes

¬£îUûUÊÑ sY

Try it

¬£îUûUÊÑ sY     :Implicit input of string U
¬               :Split
 £              :Map each element at 0-based index Y
  î             :  Slice the following to the length of U
   Uû           :    Centre pad U with spaces to length
     UÊ         :      Length of U
       Ñ        :      Multiplied by 2
         sY     :    Slice from index Y
                :Implicit output joined with newlines
\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 101 bytes

(a)=>{int L=a.Length,l=L/2;for(;l-->0;)a=" "+a+" ";for(;++l<L;)Console.WriteLine(a.Substring(l,L));};

Basically @KevinCruijssen's answer. Saves 2 bytes because string.Length doesn't need () and another 2 bytes because the second argument of string.Substring() is length rather than end Index, but then loses 2 bytes because Console.WriteLine() is longer. I had a more naive implementation, but it was about twice as long so...

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

jq, 41 39 bytes

(length/2*" "+.)[./""|keys[]:][:length]

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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