104
\$\begingroup\$

Hold up..... this isn't trolling.


Background

These days on YouTube, comment sections are littered with such patterns:

S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S

where String is a mere placeholder and refers to any combination of characters. These patterns are usually accompanied by a It took me a lot of time to make this, pls like or something, and often the OP succeeds in amassing a number of likes.


The Task

Although you've got a great talent of accumulating upvotes on PPCG with your charming golfing skills, you're definitely not the top choice for making witty remarks or referencing memes in YouTube comment sections. Thus, your constructive comments made with deliberate thought amass a few to no 'likes' on YouTube. You want this to change. So, you resort to making the abovementioned clichéd patterns to achieve your ultimate ambition, but without wasting any time trying to manually write them.

Simply put, your task is to take a string, say s, and output 2*s.length - 1 substrings of s, delimited by a newline, so as to comply with the following pattern:

(for s = "Hello")

H
He
Hel
Hell
Hello
Hell
Hel
He
H

Input

A single string s. Input defaults of the community apply. You can assume that the input string will only contain printable ASCII characters.


Output

Several lines separated by a newline, constituting an appropriate pattern as explained above. Output defaults of the community apply. Leading and trailing blank (containing no characters or characters that cannot be seen, like a space) lines in the output are permitted.


Test Case

A multi-word test case:

Input => "Oh yeah yeah"

Output =>

O
Oh
Oh 
Oh y
Oh ye
Oh yea
Oh yeah
Oh yeah 
Oh yeah y
Oh yeah ye
Oh yeah yea
Oh yeah yeah
Oh yeah yea
Oh yeah ye
Oh yeah y
Oh yeah 
Oh yeah
Oh yea
Oh ye
Oh y
Oh 
Oh
O

Note that there are apparent distortions in the above test case's output's shape (for instance, line two and line three of the output appear the same). Those are because we can't see the trailing whitespaces. Your program need NOT to try to fix these distortions.


Winning Criterion

This is , so the shortest code in bytes in each language wins!

\$\endgroup\$
12
  • 23
    \$\begingroup\$ I am planning to make some more YouTube comments related challenges in the future; hence the YouTube Comments #1 in the title. \$\endgroup\$
    – Arjun
    Feb 27, 2019 at 10:31
  • 1
    \$\begingroup\$ Is returning a array of lines allowed? \$\endgroup\$ Feb 27, 2019 at 11:00
  • 2
    \$\begingroup\$ Can we take input as an array of characters and return an array of arrays of characters? \$\endgroup\$
    – Shaggy
    Feb 27, 2019 at 11:43
  • 3
    \$\begingroup\$ Closely related \$\endgroup\$
    – Giuseppe
    Feb 27, 2019 at 15:49
  • 3
    \$\begingroup\$ Can the input be ""? What about a single character like "H"? If so, what should be the output for both of those cases? \$\endgroup\$ Feb 27, 2019 at 20:41

90 Answers 90

120
\$\begingroup\$

brainfuck, 32 bytes

,[[<]>[.>]++++++++++.,[>>]<[-]<]

Try it online!

The same loop is used for both halves of the pattern.

Explanation:

,             Take first input character as initial line
[             Until line to output is empty:
  [<]>        Move to beginning of line
  [.>]        Output all characters in line
  ++++++++++. Output newline
  ,           Input next character
  [>>]        Move two cells right if input character nonzero
  <[-]        Otherwise remove last character in line
  <           Move to new last character in line
]
\$\endgroup\$
2
  • 2
    \$\begingroup\$ That's just plain awesome. I was trying to do something in brainfuck but it came out about 10 times this long and still didn't work properly. \$\endgroup\$
    – ElPedro
    Feb 27, 2019 at 22:09
  • 40
    \$\begingroup\$ Never thought I'd see a challenge where the brainfuck answer was actually scoring competitively, awesome work! \$\endgroup\$ Feb 28, 2019 at 18:01
55
\$\begingroup\$

JavaScript (ES6), 36 bytes

f=([c,...r],s=`
`)=>c?s+f(r,s+c)+s:s

Try it online!

Commented

f = (             // f is a recursive function taking:
                  //   the input string split into:
  [c,             //     c   = next character (may be undefined if we've reached the end)
      ...r],      //     r[] = array of remaining characters
  s = `\n`        //   the output string s, initialized to a linefeed
) =>              // 
  c ?             // if c is defined:
    s +           //   append s (top of the ASCII art)
    f(r, s + c) + //   append the result of a recursive call to f, using r[] and s + c
    s             //   append s again (bottom of the ASCII art)
  :               // else:
    s             //   append s just once (this is the final middle row) and stop recursion
\$\endgroup\$
4
  • 3
    \$\begingroup\$ very nice answer :D \$\endgroup\$
    – lois6b
    Feb 27, 2019 at 15:38
  • \$\begingroup\$ different OSes different sizes got to hate line endings so windows reports as 37 bytes because of \r\n over Unix \n :D \$\endgroup\$ Feb 27, 2019 at 16:57
  • 11
    \$\begingroup\$ @MartinBarker On Windows, I'm using Notepad++ with the default Line Ending turned to Unix (LF). Problem solved once and for all. :) \$\endgroup\$
    – Arnauld
    Feb 27, 2019 at 17:00
  • \$\begingroup\$ Longer than the BF solution...that's a first \$\endgroup\$ Oct 31, 2019 at 3:02
50
\$\begingroup\$

05AB1E (legacy),  4  3 bytes

Crossed out &nbsp;4&nbsp; is no longer 4 :)

η.∊

Try it online or verify all test cases.

Explanation:

η     # Get the prefixes of the (implicit) input-string
 .∊   # Vertically mirror everything with the last line overlapping
      # (which implicitly joins by newlines in the legacy version of 05AB1E)
      # (and output the result implicitly)

In the new version of 05AB1E, and explicit » is required after the η, which is why I use the legacy version of 05AB1E here to save a byte.


3 bytes alternative provided by @Grimy:

ηû»

This version works in both the legacy and new version of 05AB1E.

Try it online (legacy), try it online (new version) or verify all test cases (new version).

Explanation:

η     # Get all prefixed of the (implicit) input-string
 û    # Palindromize each string in this list
  »   # And then join the list of strings by newlines
      # (after which the result is output implicitly)
\$\endgroup\$
12
  • 7
    \$\begingroup\$ Hmm, this seems to 6 bytes in UTF8: \xce\xb7\x2e\xe2\x88\x8a \$\endgroup\$
    – rubenvb
    Feb 28, 2019 at 17:22
  • 11
    \$\begingroup\$ @rubenvb In UTF-8 it's indeed more. 05AB1E uses, just like some some of the programming languages used in other answers (i.e. Jelly; Japt; Charcoal) it's own source code (which is CP-1252 in the case of 05AB1E), where each of the 256 characters it knows is a single byte. \$\endgroup\$ Feb 28, 2019 at 17:30
  • \$\begingroup\$ All right, fair enough :). \$\endgroup\$
    – rubenvb
    Feb 28, 2019 at 17:31
  • 9
    \$\begingroup\$ @hanshenrik Good question. It is indeed not CP-1252, but in fact the 05AB1E encoding, which is the custom encoding it uses. The bytes of this code in hex are 08 2e 17, which you can run and verify with the --osabie flag: tio.run/… \$\endgroup\$
    – Adnan
    Mar 2, 2019 at 12:20
  • 1
    \$\begingroup\$ ηû» for modern 05AB1E. \$\endgroup\$
    – Grimmy
    Oct 31, 2019 at 16:54
25
\$\begingroup\$

x86-16 machine code, IBM PC DOS,  44  43 39 bytes

00000000: d1ee ad8b d648 93b7 248a cbd0 e13a d975  .....H..$....:.|
00000010: 01fd ac86 3cb4 09cd 2186 3cb8 0d0e cd10  ....<...!.<.....
00000020: b00a cd10 e2e7 c3                        .......

Build and test YT.COM using xxd -r from above.

Unassembled:

D1 EE       SHR  SI, 1              ; point SI to DOS PSP at 80H (SI intialized at 100H) 
AD          LODSW                   ; load input length into AL, SI = 82H 
8B D6       MOV  DX, SI             ; save start of string pointer 
48          DEC  AX                 ; remove leading space from string length 
93          XCHG AX, BX             ; save string length in BL
B7 24       MOV  BH, '$'            ; put end-of-string marker in BH
8A CB       MOV  CL, BL             ; set up loop counter in CL
D0 E1       SHL  CL, 1              ; number of lines = 2 * string length - 1
    LINE_LOOP:
3A D9       CMP  BL, CL             ; does CL = string length?
75 01       JNZ  LINE_OUT           ; if not, go to output line
FD          STD                     ; otherwise flip DF to descend
    LINE_OUT: 
AC          LODSB                   ; increment or decrement SI
86 3C       XCHG BH, [SI]           ; swap current string byte with end of string delimiter 
B4 09       MOV  AH, 9              ; DOS API display string function 
CD 21       INT  21H                ; write substring to console 
86 3C       XCHG BH, [SI]           ; restore string byte 
B8 0E0D     MOV  AX, 0E0DH          ; AH = 0EH (BIOS tty function), AL = CR char
CD 10       INT  10H                ; write CR to console
B0 0A       MOV  AL, 0AH            ; AL = LF char
CD 10       INT  10H                ; write LF to console
E2 E6       LOOP LINE_LOOP          ; move to next line 
C3          RET                     ; return to DOS

Explanation

Loop 2 * input length - 1 for each row. The DOS API's string display function (INT 21H,9) writes a $-terminated string to the screen, so each time through the loop the character after the last to be displayed is swapped with the end-of-string terminator.

The loop counter is compared with the string length, and if it's greater (meaning the ascending part of the output) the string/swap position is incremented, otherwise it's decremented.

Standalone PC DOS executable program, takes input string from command line.

Output

enter image description here

  • -1 byte use SHR SI, 1 instead of MOV - thanks to gastropner!
  • -1 byte flipping loop comparison
  • -1 byte write newline directly instead of as string
  • -1 byte use XCHG instead of MOV
  • -1 byte use STD / LODSB to ascend/descend SI pointer
\$\endgroup\$
6
  • 1
    \$\begingroup\$ Most DOS flavours have SI = 100h upon loading a COM file. This can save you a byte by replacing the first instruction with SHR SI, 1. \$\endgroup\$
    – gastropner
    Mar 8, 2019 at 14:32
  • \$\begingroup\$ @gastropner very clever! Turns out the original won't run on DOS 1.0 anyway since it counts on CH being 0 (would cost +2 bytes to initialize, which isn't worth it just for DOS 1). Updated with new version! \$\endgroup\$
    – 640KB
    Mar 8, 2019 at 15:11
  • \$\begingroup\$ Do you have to enter the date everytime you open the terminal? \$\endgroup\$
    – user14492
    Sep 2, 2019 at 12:31
  • 1
    \$\begingroup\$ @user14492 ha, no! I just forgot to crop that part out of the DOS screenshot! \$\endgroup\$
    – 640KB
    Sep 2, 2019 at 12:58
  • \$\begingroup\$ Is this assembler ? It's the first time I see this since my student time. (= long, long ago) \$\endgroup\$
    – Conffusion
    Nov 3, 2020 at 10:41
20
\$\begingroup\$

MATL, 8 bytes

nZv"G@:)

Try it online!

Please like this post for the smiley :) in the code it took me a lot of time to make.

n  % Length of the input string
Zv % Symmetric range ([1 2 ... n ... 1])
"  % For each k in above range
G  % Push input
@: % Push [1 2 ... k]
)  % Index
\$\endgroup\$
19
\$\begingroup\$

Python 2, 60 52 bytes

f=lambda s,n=1:s[n:]and[s[:n]]+f(s,n+1)+[s[:n]]or[s]

Try it online!

Python 3.8 (pre-release), 50 bytes

f=lambda s,n=1:s>(x:=s[:n])and[x,*f(s,n+1),x]or[s]

Try it online!

\$\endgroup\$
6
  • 2
    \$\begingroup\$ Does this depend on a forthcoming feature of 3.8? Which feature? \$\endgroup\$
    – alexis
    Feb 27, 2019 at 17:58
  • 7
    \$\begingroup\$ @alexis This is using an assignment expression: x:=s[:n]. \$\endgroup\$
    – Arnauld
    Feb 27, 2019 at 19:35
  • 1
    \$\begingroup\$ Ah, I see it now thanks :-) I've read about the feature before, looking forward to it. Still miss it from my C days... \$\endgroup\$
    – alexis
    Feb 28, 2019 at 7:37
  • 1
    \$\begingroup\$ These don't print the output though. They just make the array, right? \$\endgroup\$ Mar 3, 2019 at 17:13
  • 1
    \$\begingroup\$ @JadenTravnik It's a lambda expression (an anonymous function), and functions are allowed by default. \$\endgroup\$
    – MilkyWay90
    Jun 14, 2019 at 17:12
16
\$\begingroup\$

J, 11 bytes

Anonymous tacit prefix function. Returns a space-padded character matrix.

[:(}:,|.)]\

Try it online!

]\ the list of prefixes

[:() apply the following function to that list

|. the reverse list

, prepended with

}: the curtailed (without last item) list

\$\endgroup\$
2
  • 18
    \$\begingroup\$ [:( and }:,| look so sad… \$\endgroup\$
    – Adám
    Feb 27, 2019 at 11:57
  • \$\begingroup\$ But it's (}: which is a happy person with a fancy mustache \$\endgroup\$
    – DonFusili
    Mar 6, 2019 at 9:33
13
\$\begingroup\$

Perl 6, 31 bytes

{[\~](@_)[0...@_-1...0]}o*.comb

Try it online!

Anonymous code block that takes a string and returns a list of lines.

Explanation:

{                      }o*.comb   # Pass the list of characters into the codeblock
 [\~](@_)                 # Triangular reduce by concatenation
                          # e.g. The list [1,2,3,4] turns into [1,12,123,1234]
         [0...@_-1        # Return the elements from 0 to length of string minus 1
                  ...0]   # And back down to 0
\$\endgroup\$
2
  • 5
    \$\begingroup\$ It's funny that these days even golfed Perl is among the most readable contestants. \$\endgroup\$ Mar 1, 2019 at 6:14
  • 7
    \$\begingroup\$ @ceasedtoturncounterclockwis Well, this is Perl 6. The Perl 5 answer is still unreadable \$\endgroup\$
    – Jo King
    Mar 1, 2019 at 7:00
11
\$\begingroup\$

Japt -R, 4 bytes

å+ ê

Cumulative reduce on a string.

-1 byte thanks to @Shaggy

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ Sceptic about the "-R" that has to be included in the string (without it the output doesnt work) \$\endgroup\$ Feb 27, 2019 at 14:58
  • 3
    \$\begingroup\$ @FlyingThunder Be a skeptic no more :) see here \$\endgroup\$
    – Quintec
    Feb 27, 2019 at 15:11
  • \$\begingroup\$ @Quintec, I've taken to linking the flags in my solution headers to that meta post to try to preempt these sorts of comments. \$\endgroup\$
    – Shaggy
    Feb 27, 2019 at 18:02
  • 1
    \$\begingroup\$ Pretty sure convention is <language> + -flag or <language> -flag. Also, :| I forgot cumulative reduce was a thing, I swear I skipped over it every time I saw it \$\endgroup\$
    – ASCII-only
    Mar 1, 2019 at 11:53
  • \$\begingroup\$ @ASCII-only Same, I only remembered it because I was thinking how I would solve this in APL and said "I wonder if Japt has this builtin". Also, didn't I use <language> -flag? \$\endgroup\$
    – Quintec
    Mar 1, 2019 at 14:01
10
\$\begingroup\$

Perl 5 (-p), 26 bytes

s,.,$\=$`.$/.$\;"$`$&
",ge

TIO

\$\endgroup\$
0
10
+300
\$\begingroup\$

Japt -R, 9 7 bytes

-2 bytes thanks to Shaggy

Êõ@¯XÃê

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ 7 bytes \$\endgroup\$
    – Shaggy
    Feb 27, 2019 at 11:43
  • 1
    \$\begingroup\$ @Shaggy oh wait... Ã is a thing \$\endgroup\$
    – ASCII-only
    Feb 27, 2019 at 11:47
  • \$\begingroup\$ Another 300 rep on its way as soon as this question is eligible for a bounty. \$\endgroup\$
    – Shaggy
    Feb 27, 2019 at 13:06
  • 1
    \$\begingroup\$ 5 bytes? (different approach) \$\endgroup\$
    – Quintec
    Feb 27, 2019 at 14:14
  • 1
    \$\begingroup\$ @Quintec, cumulative reduce works on strings, too, so you don't need to split at the start. I'd also say that's different enough to warrant posting it yourself. \$\endgroup\$
    – Shaggy
    Feb 27, 2019 at 14:38
9
\$\begingroup\$

Haskell, 52 50 44 bytes

f x=unlines$init<>reverse$scanr(\_->init)x x

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to the site. inits requires an import to be used so you are going to need to add import Data.List or something similar. \$\endgroup\$
    – Wheat Wizard
    Feb 27, 2019 at 21:16
  • \$\begingroup\$ @SriotchilismO'Zaic Wasn't sure if that was necessary to count or not. Added, thanks! \$\endgroup\$ Feb 27, 2019 at 22:04
  • 4
    \$\begingroup\$ Also I should mention we have a chat room for talking Haskell golfing. If you have any thoughts or questions that's a great place. \$\endgroup\$
    – Wheat Wizard
    Feb 27, 2019 at 22:21
  • 1
    \$\begingroup\$ I can't believe you came up with exactly what I was going to post: import Data.List putStr.unlines.((++)<*>reverse.init).tail.inits \$\endgroup\$
    – Axman6
    Feb 28, 2019 at 5:05
8
\$\begingroup\$

R, 79 65 62 58 bytes

write(substring(s<-scan(,""),1,c(1:(r=nchar(s)),r-1:r)),1)

Try it online!

-14 by Giuseppe's superior function knowledge

-3 with cleaner indexing

-4 thanks to Nick Kennedy and Giuseppe's move to scan and write

Avoiding loops (and substr) is nice.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ loops are thoroughly unnecessary, as is sapply -- substring will do what you want (with an additional trailing empty line), and for 65 bytes! I definitely wouldn't have thought of substring if I hadn't seen your nice use of substr here. \$\endgroup\$
    – Giuseppe
    Feb 27, 2019 at 15:53
  • 1
    \$\begingroup\$ Haha, good catch! I think I've learned more about alternate functions for the same job from your edits than anywhere else at this point. \$\endgroup\$ Feb 27, 2019 at 16:01
  • 2
    \$\begingroup\$ Haha, R has a stupid amount of synonyms with subtle differences. Every time I feel like I know the best tool for the job, I find something else that's slightly better in a weird edge case... \$\endgroup\$
    – Giuseppe
    Feb 27, 2019 at 16:06
  • 3
    \$\begingroup\$ How about Try it online! using scan and write? Only 59 bytes! \$\endgroup\$ Feb 27, 2019 at 18:49
  • 1
    \$\begingroup\$ @NickKennedy 58 bytes if you replace "" with 1. \$\endgroup\$
    – Giuseppe
    Feb 27, 2019 at 19:10
6
\$\begingroup\$

Jelly, 5 4 bytes

-1 byte thanks to @JonathanAllan!

¹ƤŒḄ

Try it online! I think this is my second Jelly answer? I don't know if this is optimal. I am more convinced of it being optimal. Returns an array of lines.

Explanation

¹ƤŒḄ     input: "Hi!"
¹Ƥ       prefixes of the input: [["H"], ["H", "i"], ["H", "i", "!"]]
  ŒḄ     bounce, using each array: [["H"], ["H", "i"], ["H", "i", "!"], ["H", "i"], ["H"]]

Another approach, proposed by @JonathanAllan, is ;\ŒḄ, which cumulatively reduces (\) concatenation (;), which is another way to generate prefixes.

\$\endgroup\$
2
  • \$\begingroup\$ We are allowed to yield an array of lines, so you can bump Y out of the code (I'd make the footer either ÇY or ÇŒṘ to avoid a full-program's implicit smashing print). On a side-note this is also equivalently implemented as ;\ŒḄ for the same byte-count (also you can pass the argument as"blah" as Jelly interprets this as a list of characters - yours is actually a list of lists of characters, as you'll see if you make the footer ÇŒṘ) \$\endgroup\$ Feb 28, 2019 at 13:50
  • \$\begingroup\$ @JonathanAllan thanks! very interesting :) \$\endgroup\$ Feb 28, 2019 at 17:15
6
\$\begingroup\$

Python 3.8 (pre-release), 48 bytes

lambda s,r='':(l:=[r:=r+c for c in s])+l[-2::-1]

Try it online!

Uses assignment expressions with := to accumulate a list of prefixes and then again to save the result to concatenate its reverse (without the first char).

Python 2, 51 bytes

f=lambda s,l=[]:s and f(s[:-1],[s]+l)or l+l[-2::-1]

Try it online!

We almost have the following nice 45-byte solution, but it has the original string twice and I don't see a short way to fix this.

f=lambda s,l=[]:s and f(s[:-1],[s]+l+[s])or l

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ Wouldn't you need to add some newline and print to get the desired output? \$\endgroup\$ Mar 3, 2019 at 17:16
  • \$\begingroup\$ Something like print('\n'.join(f(s))) ? \$\endgroup\$ Mar 3, 2019 at 17:22
  • \$\begingroup\$ @JadenTravnik The community defaults (which this challenge follows) allow for functions in addition to programs. And the challenge author said in the comments that they are OK with a list of strings within joining as allowed by default, though I myself don't like this as a default and have downvoted it. See also the Python rules summary. \$\endgroup\$
    – xnor
    Mar 3, 2019 at 17:34
  • \$\begingroup\$ Huh. Ok, thanks for pointing that out. Im new ¯_(ツ)_/¯. If thats the case, here is a competing 45-byte solution: x=[s[:i+1]for i in range(len(s))];x+x[-2::-1] \$\endgroup\$ Mar 3, 2019 at 17:42
  • \$\begingroup\$ @JadenTravnik No problem, the rules are unfortunately scattered over the place. Your example though is a snippet which are not allowed. It needs to do input and output like s=input();x=[s[:i+1]for i in range(len(s))];print x+x[-2::-1]. See the examples at the top here. \$\endgroup\$
    – xnor
    Mar 3, 2019 at 17:56
5
\$\begingroup\$

Charcoal, 5 bytes

G^Lθθ

Try it online! Link is to verbose version of code. Explanation: draws a filled polygon, ^ specifies that the sides are down right and down left (the polygon then automatically closes itself), Lθ specifies the length of those sides as being the length of the original input and the final θ specifies the fill string.

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

C# (Visual C# Interactive Compiler), 123 109 94 84 74 bytes

Assumes we can return a char array array (I believe we can, as a char array is a valid representation for a string and a string array is a valid representation for multiple lines)

a=>new int[a.Length*2-1].Select((b,i)=>a.SkipLast(Math.Abs(a.Length-i-1)))

Try it online!

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

Attache, 15 bytes

Bounce@Prefixes

Try it online!

Pretty simple. Bounces (appends reverse without center) the Prefixes of the input.

Alternatively, 21 bytes: Bounce@{_[0..0:~-#_]}, re-implementing prefix.

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

Brachylog (v2), 6 bytes

a₀ᶠ⊆.↔

Try it online!

Function submission, returning an array of lines. Loosely based on @Fatalize's answer.

Explanation

a₀ᶠ⊆.↔
    .↔  Find a palindrome
   ⊆      that contains, in order,
  ᶠ       all
a₀        prefixes of {the input}

Tiebreak order here is set by the , which, when used with this flow pattern, prefers the shortest possible output, tiebroken by placing the given elements as early as possible. The shortest possible output is what we want here (due to it not being possible to have any duplicate prefixes), and placing the given elements (i.e. the prefixes) as early as possible will place them in the first half (rounded up) of the output. Given that we're also requiring them to be placed in the same order, we happen to get exactly the pattern we need even though the description we gave Brachylog is very general; the tiebreaks happen to work out exactly right, causing Brachylog to pick the output we want rather than some other output that obeys the description.

\$\endgroup\$
4
\$\begingroup\$

APL (Dyalog Unicode), 9 bytesSBCS

Anonymous tacit prefix function. Returns list of strings.

(⊢,1↓⌽),\

Try it online!

,\ the list of prefixes (lit, the cumulative concatenation)

() apply the following function to that list:

 the reversed list

1↓ drop the first item

, prepend

 the unmodified list

\$\endgroup\$
4
\$\begingroup\$

PowerShell, 46 bytes

($l=$args|% t*y|%{($s+=$_);++$i})+$l[$i..0]|gu

Try it online!


PowerShell, 42 bytes (YouTube special, dirty)

It is known that the maximum length of a comment on youtube is 10,000 characters. Ok, use this as the upper limit.

($l=$args|% t*y|%{($s+=$_)})+$l[1e4..0]|gu

Try it online!

\$\endgroup\$
4
\$\begingroup\$

sed, 31 35 bytes

:x
h
s/.\n.*\|.$//
/^$/{x;q}
H
G
bx

Try it online!

Explanation

At the beginning of each iteration of the loop, pattern space is some "central chunk" of the desired output, and each loop adds a shortened copy to the top and bottom.

:x                 
h                  Copy the current chunk to hold space
s/.\n.*\|.$//      Remove the last letter of the first line, and all other lines (if there are any)
/^$/{x;q}          If pattern space is empty we're done; output hold space
H                  Add the shortened line to the end of hold space
G                  and add the new hold space to pattern space.
bx                 
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice one, but the the middle line (the full original input) seems to be output 3 times. At least with GNU sed. Same on TIO. Which sed implementation you use and how you pass it the input? (BTW, changing the substitution to s/.\n.*\|.$// fixes it.) \$\endgroup\$
    – manatwork
    Feb 28, 2019 at 13:12
  • 2
    \$\begingroup\$ Ah, you're right. It's not a problem with my sed implementation (using GNU version 4.2.1) , I just didn't notice the bug. I've played around with some other fixes and can't find anything that adds fewer than four bytes so I'm adopting your fix, thank you. \$\endgroup\$ Feb 28, 2019 at 18:22
4
\$\begingroup\$

x86-16 machine code, IBM PC-DOS, 33 bytes

Hexdump:

00000000: bf 82 00 91 89 fa e8 0a 00 74 06 41 eb f8 e8 02  .........t.A....
00000010: 00 e2 fb b4 40 cd 21 b0 0d ae cd 29 b0 0a cd 29  ....@.!....)...)
00000020: c3                                               .

Commented assembly:

        [org 0x100]
start:
        ; DI <- first command line argument
        mov     di, 0x0082
        ; DOS startup state abuse 1: set CX to zero by swapping AX (0x0000)
        xchg    cx, ax
        ; DX <- DI
        mov     dx, di
.loop1:
        ; A multitasking loop.
        ; This both prints the string up to the full length and counts
        ; the chars by scanning for '\r'.

        ; Print DS:DX(CX)
        ; We test for the end of string when printing
        ; the newline by using SCASB.
        call    putsn
        ; If the SCASB returned true, break to the end of .loop2
        ; We don't go to the top because it would print the full
        ; length string twice.
        jz      .next
        ; Increment the length and character counter
        inc     cx
        ; Loop to loop1
        jmp     .loop1
        
.loop2: ; Shortening loop
        ; Print
        call    putsn
.next:
        ; while (--CX)
        loop    .loop2
        ; Fallthrough: prints an empty line (as CX is 0) and exits

        ; Prints CX chars from DX, followed by a newline.
putsn:
        ; DOS startup state abuse 2: BX is 0x0000.
        ; DOS lets you write to STDIN and it still prints to the screen.
        ; Why? I have no idea. It's very convenient though. Note that
        ; this behavior is consistent on DOS 6.22 and FreeDOS 1.3rc4.
        ;
        ; write(0, argv, CX)
        mov     ah, 0x40
        int     0x21
        ; Print \r\n with INT 29h
        mov     al, 13
        ; Since we have \r in AL, we can use SCASB to check
        ; for the end of the string when we return.
        ; Interrupts save the flags.
        ;
        ; Yes, this reads out of bounds on the second loop,
        ; but it is DOS, who cares?
        scasb
        int     0x29
        mov     al, 10
        int     0x29
        ret

To be even with 640KB, I also used the command line arguments, but I made some changes:

  1. I use write (21:40) instead of puts (21:09). While it does require manually printing a newline, it lets me manually control the length just by changing CX.
  2. I count the length of the command line arguments on the fly.
  3. I did some other tricks.

This abuses the newline rule: it actually prints empty strings at the start and end.

What did you expect?

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

Ruby, 51 42 40 bytes

f=->s,i=1{s[i]?[t=s[0,i],*f[s,i+1],t]:s}

Try it online!

Thanks to Doorknob for -2 bytes.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save 2 bytes by replacing ... with , \$\endgroup\$
    – Doorknob
    Feb 27, 2019 at 13:17
3
\$\begingroup\$

JavaScript (Node.js), 90 bytes

This can probably be golfed alot more, Arnauld already has a way shorter one but I had fun atleast!

s=>{a=[];for(c=s.length-1;c--;)a[c]=s.slice(0,c+1);return[...a,s,...a.reverse()].join`\n`}

Try it online!

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

SNOBOL4 (CSNOBOL4), 118 bytes

	N =INPUT
	L =1
1	X =LT(X,SIZE(N)) X + 1	:F(D)
O	N ARB . OUTPUT POS(X)	:($L)
D	X =GT(X) X - 1	:F(END)
	L ='D'	:(O)
END

Try it online!

There appears to be a bug in this implementation of SNOBOL; attempting to replace the label D with the label 2 causes an error, although the manual for Vanilla SNOBOL indicates that (emphasis added)

If a label is present, it must begin with the first character of the line. Labels provide a name for the statement, and serve as the target for transfer of control from the GOTO field of any statement. Labels must begin with a letter or digit, optionally followed by an arbitrary string of characters. The label field is terminated by the character blank, tab, or semicolon. If the first character of a line is blank or tab, the label field is absent.

My supposition is that the CSNOBOL interpreter only supports a single label that begins with an integer.

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

APL+WIN, 31 bytes

Prompts for input of string:

 ⊃((⍳n),1↓⌽⍳n)↑¨(¯1+2×n←⍴s)⍴⊂s←⎕

Explanation:

(¯1+2×n←⍴s)⍴⊂s create a nested vector of the string of length =1+2x length of string

((⍳n),1↓⌽⍳n)↑¨ progressively select elements from each element of the nested vector 
              following the pattern 1  2 ...to n to n-1 ... 1

⊃ convert nested vector into a 2d array.
\$\endgroup\$
3
\$\begingroup\$

F# (.NET Core), 67 61 bytes

let l=s.Length
[1..l*2-1]|>Seq.map(fun i->s.[..l-abs(i-l)-1])

Try it online!

Input is a string and output is a seq<string>

Another solution could be let f(s:string)=for i=1 to s.Length*2-1 do printfn"%s"s.[..s.Length-abs(i-s.Length)-1] for 80ish bytes... I am not sure that it is worth looking into.

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

Haskell, 36 bytes

foldr(\h l->(h:)<$>[]:l++min[[]]l)[]

Try it online!

Outputs a list of lines.

Haskell, 37 bytes

f[c]=[[c]]
f(h:t)=(h:)<$>"":f t++[""]

Try it online!

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

J, 12 bytes

]\,[:}.@|.]\

Try it online!

Still 1 byte longer than Adám's

K (oK), 12 11 bytes

-1 byte thanks to ngn

{x,1_|x}@,\

Try it online!

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Did I outgolf the master‽ \$\endgroup\$
    – Adám
    Feb 27, 2019 at 11:56
  • \$\begingroup\$ @Adám I'm far from being a J master :) There are many J coders here better than I am. \$\endgroup\$ Feb 27, 2019 at 12:00
  • 1
    \$\begingroup\$ -1 byte for oK: {x,1_|x}@,\ \$\endgroup\$
    – ngn
    Feb 28, 2019 at 22:31

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.