Mache einen super Akrostichon

35

Hintergrund

Wir feiern die Veröffentlichung von Dyalog APL 16.0 , wo die Lösung für dieses Problem in {⊢⌺(≢⍵)⊢⍵}Erläuterung besteht

Aufgabe

Wenn Sie eine druckbare ASCII-Zeichenfolge mit der ungeraden Länge n erhalten , machen Sie ein n × n- Quadrat, wobei die Zeichenfolge horizontal zentriert, für die vertikale Zentrierung dupliziert und in jeder Zeile und Spalte dieselbe Zeichenfolge enthalten ist. Beachten Sie, dass alle Zeichenfolgen mit Ausnahme der zentrierten Zeichenfolgen abgeschnitten werden, um die Größe des Quadrats n × n beizubehalten .

Die Erklärung Ihres Codes wird sehr geschätzt.

Regeln

  1. Möglicherweise haben Sie nachgestellte Leerzeichen und Zeilenumbrüche (dies schließt das untere rechte Dreieck ein).
  2. Sie können eine Liste von Zeichenfolgen zurückgeben

Beispiel mit dem String ABXCD:

  • n ist 5. Zuerst zeichnen wir die zwei zentrierten Zeichenketten, eine horizontale und eine vertikale:

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

    (5 × 5-Begrenzungsrahmen zur Verdeutlichung hinzugefügt)

  • Dann platzieren wir alle möglichen Akrostiken horizontal und vertikal:

           EIN
          AB
      ┌─────┐
      │ ABX│CD
      │ ABXC│D
      │ABXCD│
     A│BXCD │
    AB│XCD │
      └─────┘
       CD
       D
    
  • Schließlich geben wir nur das zurück, was sich innerhalb des Begrenzungsrahmens befindet:

      ABX
     ABXC
    ABXCD
    BXCD 
    XCD  
    

Testfälle

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

Danksagung

Vielen Dank an Dzaima , Leaky Nun , Mr. Xcoder für alles andere als die Idee dieser Herausforderung.

Adam
quelle
1
Müssen die Leerzeichen rechts unten eingefügt werden oder nicht?
Fehler
1
@flawr OP: Mai
Adám

Antworten:

5

MATL , 8 Bytes

nXyPGZ+c

Probieren Sie es online!

Erläuterung

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
Luis Mendo
quelle
1
Wer hätte gedacht, dass mir diese Antwort
gefallen
1
@flawr Ja, wer hätte das gedacht
Luis Mendo
4

Retina , 70 59 Bytes

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

Probieren Sie es online! Bearbeiten: 11 Bytes mit Hilfe von @MartinEnder gespeichert. Erläuterung: In der ersten Stufe wird die Eingabe einmal für jedes Zeichen wiederholt, wobei es in jeder Zeile entsprechend aufgefüllt wird, um die Scherung zu erhalten. Die letzte Stufe entfernt dann 25% von jeder Seite, um das gewünschte Ergebnis zu erzielen.

Neil
quelle
Ich glaube ich hatte 59 früher. Sie haben keine Zeit , um jetzt die Details raben, aber im Wesentlichen in der ersten Stufe I gepolstert nur die Eingabe mit n/2Leerzeichen links und rechts (mit so etwas wie (..)+.-> $#1$* $&$#1$*mit einem nachgestellten Leerzeichen) und dann tat mir nur , !&`...wo ...Streichhölzer ngenau nZeichen.
Martin Ender
Ihr Ansatz kann mindestens auf 63 verkürzt werden: tio.run/##K0otycxL/…
Martin Ender
@MartinEnder Danke, und ich habe noch 4 Bytes Golf gespielt!
Neil
Benötigen Sie die zweite $*sp?
CalculatorFeline
@CalculatorFeline Ja, ich muss alle Zeilen gleich lang sein, damit ich sie durch 4 teilen kann.
Neil
3

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 dank @ OlivierGrégoire .

Erläuterung:

Probieren Sie es hier aus.

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
Kevin Cruijssen
quelle
i=l/2+1und i-->1und for(;i<lein Byte speichern.
Olivier Grégoire
1
Und ... total golfen: 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). Die einzige wesentliche Änderung besteht darin, dass die Zeichenfolge mit Leerzeichen ein für alle Mal generiert wird, anstatt "on the fly" (und natürlich der Ausdruck, anstatt zurückzukehren).
Olivier Grégoire
3

Haskell, 64 62 Bytes

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

Probieren Sie es online! Wie es funktioniert:

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
nimi
quelle
3

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

Vielleicht versuchen Sie es hier online: http://swish.swi-prolog.org/p/hEKigfEl.pl

NB.

  1. Die letzte Zeile ist eine lange Zeile. Ich habe hier einen Zeilenumbruch und Leerzeichen eingefügt, um horizontale Bildlaufleisten in dieser Antwort zu vermeiden.
  2. Die Frage beinhaltet Leerzeichen zum Auffüllen, aber Swish Online zeigt sie aufgrund von HTML-Rendering-Interaktionen nicht sauber an. Sie müssen den Quellcode in den Browser-Entwicklungstools anzeigen, um zu überprüfen, ob sie vorhanden sind (sind). Ich habe das Auffüllen geändert, um _hier zu sein, da es zeigt, dass es funktioniert und die Byteanzahl nicht beeinflusst.

Beispiele, die in Swish laufen:

Testfälle

Annäherung, im Grunde das erste, was ich überhaupt zum Arbeiten bringen könnte, und zweifellos könnte ein erfahrener Prolog-Benutzer es sehr verkürzen:

  • Bei einer Zeichenfolge mit der Länge L hat die Ausgabe L Zeilen und jede Zeile ist L Zeichen lang, sodass "L" häufig vorkommt. Countdown von L bis 0 für die Anzahl der Zeilen, L für die Länge der Teilzeichenfolge für jede Zeile.
  • Erstellen Sie eine Füllzeichenfolge mit einer Länge von L Leerzeichen (Unterstrichen), und fügen Sie sie an beiden Enden der Eingabezeichenfolge hinzu, da dies eine einfache Länge ist, die auf jeden Fall ausreichen wird.
  • Berechnen Sie einen Anfangsoffset für diese dreifach lange Zeichenfolge und rekursieren Sie, wobei Sie jedes Mal eine Teilzeichenfolge erstellen, in eine Ergebnisliste.

Erklärter und kommentierter Code (wird möglicherweise nicht ausgeführt), von superacrostic()unten gelesen , dann helper()Hauptteil, dann helper()Basisfall:

% 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'.
TessellatingHeckler
quelle
2

05AB1E , 11 Bytes

g;úIvDIg£,À

Probieren Sie es online!

Erläuterung

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
Emigna
quelle
2

JavaScript (ES6), 75 Byte

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

Arnauld
quelle
72 Bytes . Oder 70 Bytes, wenn Sie wie ich mit ES8 arbeiten möchten.
Shaggy
2

APL (Dyalog Unicode) , 10 Zeichen = 22 Byte

{⊢⌺(≢⍵)⊢⍵}

Probieren Sie es online!

{} Anonyme Funktion, bei der das Argument durch ⍵ dargestellt wird

 Geben Sie den abgedeckten Bereich an, wenn

⌺() Eine Schablone der Größe schieben

   Länge von

   das Argument

 auf

 das Argument

Dies funktioniert, indem jedes Zeichen die Mitte einer Zeichenfolge mit der gleichen Länge wie die Eingabe bildet und nach Bedarf nach links oder rechts aufgefüllt wird. Nimm zBABXCD :

Die Zeichenfolge besteht aus fünf Zeichen, sodass die Schablone eine "Öffnung" mit einer Breite von fünf Zeichen aufweist.

┌──↓──┐     Schablonenöffnung mit mittlerem Marker
│ ABX│CD   lassen Sie Ain der Mitte sein ,
 │ ABXC│D   dann B
  │ABXCD|   usw.
  A|BXCD | 
  AB|XCD  |
    └──↑──┘ endgültige Schablonenposition

Adam
quelle
2

PHP , 98 Bytes

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

Probieren Sie es online!

Jörg Hülsermann
quelle
2

JavaScript (ES8), 66 63 62 Bytes

Gibt ein Array zurück.

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

Versuch es

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>


Erläuterung

s=>

Anonyme Funktion, die die Zeichenfolge als Argument über Parameter verwendet s.

[...s]

Teilen Sie die Zeichenfolge in ein Array einzelner Zeichen auf.

l=s.length

Rufen Sie die Länge der Zeichenfolge ab und weisen Sie sie der Variablen zu l.

.map((_,x)=>                                        )

Ordnen Sie dem Array zu, indem Sie jedes Element durch eine Funktion leiten, wobei xder Index des aktuellen Elements ist.

s.padStart(l*1.5)

Geben Sie für jedes Element die ursprüngliche Zeichenfolge mit vorangestellten Leerzeichen zurück, bis die Länge das 1,5-fache der ursprünglichen Länge beträgt.

.substr(x,l)

Liefert den Teilstring der Länge lbeginnend mit dem Index des aktuellen Elements.

Zottelig
quelle
2

V , 14 , 11 Bytes

òlÙxHÄ$x>>ê

Probieren Sie es online!

3 Bytes gespart dank @nmjmcman!

Hexdump:

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

Ursprünglicher Ansatz (18 Bytes):

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

Erläuterung:

ò           " 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.
DJMcMayhem
quelle
Sparen Sie ein paar Bytes: Probieren Sie es online!
nmjcman101
@ nmjcman101 Ah, das ist genial! Ich habe es total vergessen ê. Danke :)
DJMcMayhem
2

PowerShell Core , 68 Byte

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

Probieren Sie es online!

Ungolfed Erklärung

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

}
TessellatingHeckler
quelle
1
Möchtest du die Verbindung zu ungolf machen [($_..($_+$L))]?
root
@wurzel kurze Antwort, das (geht nicht mit dem Join, es geht -join ($Padding + $Text)[0,1,2,3,4]darum, mehrere Zeichen aus einer gepolsterten Zeichenfolge für eine Ausgabezeile auszuwählen und diese zu einer Zeichenfolge zusammenzufügen, um eine kürzere Möglichkeit zu haben .SubString(). und es erzeugt die Auffüllung an Ort und Stelle und den Bereich der Zeichen an Ort und Stelle. Die vollständige Erklärung zum Ungolf wurde zu meiner Antwort hinzugefügt.
TessellatingHeckler
2

Japt , 19 17 14 Bytes

5 Bytes gespart dank @ETHproductions und @Shaggy

¬£iSp½*Ul¹tYUl

Online testen! -RFahne hinzugefügt, um mit Zeilenumbrüchen zu verbinden (Sichtbarkeitszwecke)

Erläuterung

¬£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) 
Oliver
quelle
1
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)
ETHproductions
@ETHproductions Oh yeah, thanks!
Oliver
16 bytes
Shaggy
Oder, da ein Array zurückgegeben wird, sind 14 Byte zulässig .
Shaggy
1

Jelly , 11 Bytes

LH⁶ẋ;ṫJḣ€LY

Probieren Sie es online!

Wie es funktioniert

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"
Undichte Nonne
quelle
1

QBIC , 32 Bytes

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

Mann, es ist Zeit für mich, space$zu QBIC hinzuzufügen ...

Erläuterung

  ;             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

Probelauf

Command line: acknowledgement
       acknowle
      acknowled
     acknowledg
    acknowledge
   acknowledgem
  acknowledgeme
 acknowledgemen
acknowledgement
cknowledgement
knowledgement
nowledgement
owledgement
wledgement
ledgement
edgement
steenbergh
quelle
1

Mathematica, 88 Bytes

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

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!

flawr
quelle
I could only reach 82 : Try it online!
bartavelle
@bartavelle That doesn't look right. Your right side isn't chopped.
Adám
Yep I introduced a bug! You can gain a bit by dropping your concat : Try it online!
bartavelle
And with the chopping it's 84, making your approach better! Try it online!
bartavelle
And you can save a lot more, because you don't need to return a single string, lists of strings are OK too!
bartavelle
1

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!

CalculatorFeline
quelle
1

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
}
root
quelle
1
Nice answer! Welcome to the site. :)
DJMcMayhem
1

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

quelle
(2*x+~i) to save a byte
Felipe Nardi Batista
@FelipeNardiBatista Thanks.
1

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 ' '
miles
quelle
Works with '' as the replacement.
FrownyFrog
0

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

Kamil Drakari
quelle
0

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
Taylor Scott
quelle