It took me a lot of time to make this, pls like. (YouTube Comments #1)

87

12

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!

Arjun

Posted 2019-02-27T10:29:31.233

Reputation: 4 544

20I am planning to make some more YouTube comments related challenges in the future; hence the YouTube Comments #1 in the title. – Arjun – 2019-02-27T10:31:57.553

1Is returning a array of lines allowed? – my pronoun is monicareinstate – 2019-02-27T11:00:23.830

@someone Yes, it is allowed, in accordance with standard I/O defaults – Arjun – 2019-02-27T11:09:57.880

2Can we take input as an array of characters and return an array of arrays of characters? – Shaggy – 2019-02-27T11:43:46.453

3Closely related – Giuseppe – 2019-02-27T15:49:16.650

3Can the input be ""? What about a single character like "H"? If so, what should be the output for both of those cases? – AdmBorkBork – 2019-02-27T20:41:18.150

1@AdmBorkBork No, the input cannot be "". As for "H", the desired output is H only. I am sincerely sorry for such a late reply. – Arjun – 2019-02-28T14:21:24.927

@Shaggy If the community rules allow it, then sure. – Arjun – 2019-02-28T14:25:25.557

Are leading and trailing blank lines permitted? (i.e. output is 2*s.length + 1 lines, but the first and last lines are empty) – Chronocidal – 2019-02-28T16:44:38.997

Can we assume the input only contains chars in the ASCII 32--127 range? In particular, can we assume it doesn't contain char(0)? – Luis Mendo – 2019-03-01T10:27:50.713

@Chronocidal Yes, leading and trailing blank lines are permitted. – Arjun – 2019-03-04T03:46:08.600

@LuisMendo Yes, you can assume that the input will only contain printable ASCII characters. I'll edit accordingly. – Arjun – 2019-03-04T03:47:38.000

Answers

109

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
]

Nitrodon

Posted 2019-02-27T10:29:31.233

Reputation: 9 181

2That'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. – ElPedro – 2019-02-27T22:09:22.360

38Never thought I'd see a challenge where the brainfuck answer was actually scoring competitively, awesome work! – Question Marks – 2019-02-28T18:01:45.033

54

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

Arnauld

Posted 2019-02-27T10:29:31.233

Reputation: 111 334

3very nice answer :D – lois6b – 2019-02-27T15:38:38.983

different OSes different sizes got to hate line endings so windows reports as 37 bytes because of \r\n over Unix \n :D – Martin Barker – 2019-02-27T16:57:42.050

10@MartinBarker On Windows, I'm using Notepad++ with the default Line Ending turned to Unix (LF). Problem solved once and for all. :) – Arnauld – 2019-02-27T17:00:54.813

3Awesome! Can you write an explanation for this for those who are complete newbies to JS? – Akhoy – 2019-03-01T06:31:30.937

3@Akhoy I've added a commented version. – Arnauld – 2019-03-01T11:51:21.667

3Thank you. A lot clearer now. – Akhoy – 2019-03-01T13:25:44.153

Longer than the BF solution...that's a first – Redwolf Programs – 2019-10-31T03:02:16.467

47

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)

Kevin Cruijssen

Posted 2019-02-27T10:29:31.233

Reputation: 67 575

7Hmm, this seems to 6 bytes in UTF8: \xce\xb7\x2e\xe2\x88\x8a – rubenvb – 2019-02-28T17:22:46.550

10

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

– Kevin Cruijssen – 2019-02-28T17:30:39.957

All right, fair enough :). – rubenvb – 2019-02-28T17:31:50.130

@KevinCruijssen PHP seems to think that these characters are invalid for CP-1252, but could just be a PHP bug: https://3v4l.org/UC1QE

– hanshenrik – 2019-03-02T10:02:37.060

@rubenvb i'm still not convinced that CP-1252 is the answer here, see above.. =/ (PS: php-strings are byte arrays, the string length of a php string is always the number of bytes.) – hanshenrik – 2019-03-02T10:06:55.567

@hanshenrik Tbh, I'm not 100% sure if it's CP-1252. All I know is that the linked code-page (the first link in my first comment, or the link in the bytes of the answer-title; so this one) is the code page 05AB1E uses. I've heard somewhere it's CP-1252, but maybe I'm mistaken in that and it's a custom codepage instead. I do know that those 256 characters are 1 byte each for 05AB1E programs.

– Kevin Cruijssen – 2019-03-02T11:06:50.587

@KevinCruijssen hmm, can you take a screenshot of your source code file opened in a hex editor? (if you don't have a hex editor nearby, HxD is a great hex editor for windows systems, and Bless is a decent hex editor for Linux ) - or can you upload your source code file on some file sharing website like http://mega.co.nz ?

– hanshenrik – 2019-03-02T11:16:06.557

come to think of it, if you're on linux, you can probably just do cat source.file | base64 | pastebinit – hanshenrik – 2019-03-02T11:22:33.013

8

@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: https://tio.run/##S0oszvifnJ@SaqsUU2FgEVNhlBpTYWiu9D81OSNfQTdPQTdVQQUkr2CnUJJaXKKXmJTKVVBZkpGfZ6ygn19Qom9gmphkmKqfX5yYlJmqV1CpoKsLYcPV//@fmJSckgoA

– Adnan – 2019-03-02T12:20:09.373

@Adnan well that satisfies my curiosity, thanks guys! – hanshenrik – 2019-03-02T12:44:28.857

1ηû» for modern 05AB1E. – Grimmy – 2019-10-31T16:54:22.370

@Grimmy Ah, nice one. That one works in both 05AB1E versions. I've added it to the answer. – Kevin Cruijssen – 2019-10-31T17:17:45.970

20

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!

TFeld

Posted 2019-02-27T10:29:31.233

Reputation: 19 246

2Does this depend on a forthcoming feature of 3.8? Which feature? – alexis – 2019-02-27T17:58:46.217

7

@alexis This is using an assignment expression: x:=s[:n].

– Arnauld – 2019-02-27T19:35:39.367

1Ah, I see it now thanks :-) I've read about the feature before, looking forward to it. Still miss it from my C days... – alexis – 2019-02-28T07:37:24.623

1These don't print the output though. They just make the array, right? – Jaden Travnik – 2019-03-03T17:13:12.113

@JadenTravnik Python automatically dupms the last expression result if running interactively through a console – Xeverous – 2019-03-04T23:20:48.057

@JadenTravnik It's a lambda expression (an anonymous function), and functions are allowed by default. – MilkyWay90 – 2019-06-14T17:12:33.503

20

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

640KB

Posted 2019-02-27T10:29:31.233

Reputation: 7 149

1Most 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. – gastropner – 2019-03-08T14:32:53.613

@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! – 640KB – 2019-03-08T15:11:51.577

Do you have to enter the date everytime you open the terminal? – user14492 – 2019-09-02T12:31:35.547

1@user14492 ha, no! I just forgot to crop that part out of the DOS screenshot! – 640KB – 2019-09-02T12:58:32.410

19

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

Sanchises

Posted 2019-02-27T10:29:31.233

Reputation: 8 530

17

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

Adám

Posted 2019-02-27T10:29:31.233

Reputation: 37 779

18[:( and }:,| look so sad… – Adám – 2019-02-27T11:57:30.747

But it's (}: which is a happy person with a fancy mustache – DonFusili – 2019-03-06T09:33:37.340

14

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

Jo King

Posted 2019-02-27T10:29:31.233

Reputation: 38 234

5It's funny that these days even golfed Perl is among the most readable contestants. – ceased to turn counterclockwis – 2019-03-01T06:14:54.420

7

@ceasedtoturncounterclockwis Well, this is Perl 6. The Perl 5 answer is still unreadable

– Jo King – 2019-03-01T07:00:10.333

12

Japt -R, 4 bytes

å+ ê

Cumulative reduce on a string.

-1 byte thanks to @Shaggy

Try it online!

Quintec

Posted 2019-02-27T10:29:31.233

Reputation: 2 801

Sceptic about the "-R" that has to be included in the string (without it the output doesnt work) – Flying Thunder – 2019-02-27T14:58:21.983

3

@FlyingThunder Be a skeptic no more :) see here

– Quintec – 2019-02-27T15:11:20.537

@Quintec, I've taken to linking the flags in my solution headers to that meta post to try to preempt these sorts of comments. – Shaggy – 2019-02-27T18:02:03.757

1Pretty 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 – ASCII-only – 2019-03-01T11:53:35.120

@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? – Quintec – 2019-03-01T14:01:35.407

@Quintec but you linked to a meta post, not enclosed it in a codeblock (actually, you can even do both) – ASCII-only – 2019-03-01T22:34:46.657

11

Japt -R, 9 7 bytes

-2 bytes thanks to Shaggy

Êõ@¯XÃê

Try it online!

ASCII-only

Posted 2019-02-27T10:29:31.233

Reputation: 4 687

7 bytes – Shaggy – 2019-02-27T11:43:07.417

1@Shaggy oh wait... Ã is a thing – ASCII-only – 2019-02-27T11:47:11.670

Another 300 rep on its way as soon as this question is eligible for a bounty. – Shaggy – 2019-02-27T13:06:27.150

15 bytes? (different approach) – Quintec – 2019-02-27T14:14:20.050

1@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. – Shaggy – 2019-02-27T14:38:53.923

@Shaggy Ok, will do. – Quintec – 2019-02-27T14:40:21.243

10

Perl 5 (-p), 26 bytes

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

TIO

Nahuel Fouilleul

Posted 2019-02-27T10:29:31.233

Reputation: 5 582

10

Haskell, 52 50 44 bytes

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

Try it online!

Joseph Sible-Reinstate Monica

Posted 2019-02-27T10:29:31.233

Reputation: 556

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. – Post Rock Garf Hunter – 2019-02-27T21:16:34.657

@SriotchilismO'Zaic Wasn't sure if that was necessary to count or not. Added, thanks! – Joseph Sible-Reinstate Monica – 2019-02-27T22:04:09.233

4

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.

– Post Rock Garf Hunter – 2019-02-27T22:21:42.803

1I can't believe you came up with exactly what I was going to post:

putStr.unlines.((++)<*>reverse.init).tail.inits```
 – Axman6  – 2019-02-28T05:05:28.903

9

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.

CriminallyVulgar

Posted 2019-02-27T10:29:31.233

Reputation: 501

2

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.

– Giuseppe – 2019-02-27T15:53:25.433

1Haha, good catch! I think I've learned more about alternate functions for the same job from your edits than anywhere else at this point. – CriminallyVulgar – 2019-02-27T16:01:15.287

2Haha, 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... – Giuseppe – 2019-02-27T16:06:20.643

3

How about Try it online! using scan and write? Only 59 bytes!

– Nick Kennedy – 2019-02-27T18:49:10.183

1@NickKennedy 58 bytes if you replace "" with 1. – Giuseppe – 2019-02-27T19:10:31.217

@Giuseppe thanks, didn’t know that. It also seems that using 2 outputs to stderr. – Nick Kennedy – 2019-02-27T20:07:52.370

@NickKennedy that's neat, I couldn't find a way to use scan that didn't add more bytes. Will have to look into how write works, never really used it before. – CriminallyVulgar – 2019-02-28T10:35:36.497

7

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!

xnor

Posted 2019-02-27T10:29:31.233

Reputation: 115 687

Wouldn't you need to add some newline and print to get the desired output? – Jaden Travnik – 2019-03-03T17:16:51.407

Something like print('\n'.join(f(s))) ? – Jaden Travnik – 2019-03-03T17:22:20.933

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

– xnor – 2019-03-03T17:34:12.113

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] – Jaden Travnik – 2019-03-03T17:42:55.300

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

– xnor – 2019-03-03T17:56:48.857

Ah, ok. Thanks for pointing that out. :) – Jaden Travnik – 2019-03-03T17:59:59.077

7

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.

Conor O'Brien

Posted 2019-02-27T10:29:31.233

Reputation: 36 228

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 ÇŒṘ) – Jonathan Allan – 2019-02-28T13:50:36.380

@JonathanAllan thanks! very interesting :) – Conor O'Brien – 2019-02-28T17:15:04.850

6

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!

my pronoun is monicareinstate

Posted 2019-02-27T10:29:31.233

Reputation: 3 111

6

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.

Neil

Posted 2019-02-27T10:29:31.233

Reputation: 95 035

5

PowerShell, 89 87 66 bytes

-2 bytes thanks to @AdmBorkBork

param($a)0..($d=$a.Length-1)|%{$b+=,-join$a[0..$_]};$b+$b[--$d..0]

Try it online!

It actually didn't work as specified before, sorry about that! I've edited it and also managed to shave some bytes off.

Gabriel Mills

Posted 2019-02-27T10:29:31.233

Reputation: 778

You can --$d instead of ($d-1) to save a couple at the end. – AdmBorkBork – 2019-02-27T16:14:05.213

@AdmBorkBork Thanks. – Gabriel Mills – 2019-02-27T22:19:44.140

This doesn't work for single-character input, sadly. – AdmBorkBork – 2019-02-28T15:09:19.183

5

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.

Conor O'Brien

Posted 2019-02-27T10:29:31.233

Reputation: 36 228

5

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.

ais523

Posted 2019-02-27T10:29:31.233

Reputation: 11

5

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!

mazzy

Posted 2019-02-27T10:29:31.233

Reputation: 4 832

4

C (gcc), 68 67 64 59 bytes

thanks @ceilingcat for -6 thanks @gastropner for -5

i,j;f(char*s){for(j=1;i+=j;puts(""))j-=2*!s[write(1,s,i)];}

Try it online!

buttercrab

Posted 2019-02-27T10:29:31.233

Reputation: 169

Does not appear to be reusable. – gastropner – 2019-02-28T12:50:19.963

@gastropner what do you mean, not reusable? – Baldrickk – 2019-02-28T17:12:31.007

@Baldrickk If you call the function again with a new string, it doesn't work. – gastropner – 2019-02-28T17:13:45.860

@gastropner so? Since when was that a requirement? It works fine running the program again with a new string. – Baldrickk – 2019-02-28T17:16:21.370

3

@Baldrickk https://codegolf.meta.stackexchange.com/a/4940/758869

– gastropner – 2019-02-28T18:32:54.517

Umm... if you want to reusable version you can make it by adding j=0 3 bytes in the first for statement. – buttercrab – 2019-03-01T03:49:30.170

159 bytes – gastropner – 2019-03-08T14:05:16.433

4

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.

Kirill L.

Posted 2019-02-27T10:29:31.233

Reputation: 6 693

1You can save 2 bytes by replacing ... with , – Doorknob – 2019-02-27T13:17:28.127

4

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!

Galen Ivanov

Posted 2019-02-27T10:29:31.233

Reputation: 13 815

2

Did I outgolf the master‽

– Adám – 2019-02-27T11:56:03.953

@Adám I'm far from being a J master :) There are many J coders here better than I am. – Galen Ivanov – 2019-02-27T12:00:16.117

1

-1 byte for oK: {x,1_|x}@,\

– ngn – 2019-02-28T22:31:57.450

@ngn Thank you! – Galen Ivanov – 2019-03-01T04:51:58.517

4

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

Adám

Posted 2019-02-27T10:29:31.233

Reputation: 37 779

4

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!

T. Dirks

Posted 2019-02-27T10:29:31.233

Reputation: 176

4

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.

Giuseppe

Posted 2019-02-27T10:29:31.233

Reputation: 21 077

4

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.

Graham

Posted 2019-02-27T10:29:31.233

Reputation: 3 184

4

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.

aloisdg moving to codidact.com

Posted 2019-02-27T10:29:31.233

Reputation: 1 767

4

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                 

Sophia Lechner

Posted 2019-02-27T10:29:31.233

Reputation: 1 200

1Nice 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.) – manatwork – 2019-02-28T13:12:46.077

2Ah, 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. – Sophia Lechner – 2019-02-28T18:22:05.417

4

Python 2, 131 100 84 bytes

My first answer on Code Golf!

-47 bytes overall thanks to @SriotchilismO'Zaic

a,b=[],len(x)
for i in range(2*b-1):
 if i<b:a+=x[i]
 else:a=a[:-1]
 print''.join(a)

Try it online!

Yoni Matz

Posted 2019-02-27T10:29:31.233

Reputation: 41

1

Welcome to PCG! Be sure to read the tour and code of conduct. Good solution!

– akozi – 2019-02-28T17:02:43.150

2For python you can use ;s instead of newlines to avoid the indentation. Also no need for spaces between print and '' – Post Rock Garf Hunter – 2019-02-28T17:20:19.070

Thanks for the tips @SriotchilismO'Zaic, really helped reduce my byte count! – Yoni Matz – 2019-02-28T20:14:40.913

I'm also wondering why you put the print''.join(a) inside of the if and else. It looks like you could put it after them both to avoid repetition since its run either way. – Post Rock Garf Hunter – 2019-02-28T21:38:36.743

And you can probably save a byte by using i<b and switching your conditions. – Post Rock Garf Hunter – 2019-02-28T21:43:06.323

2And one last thing, if you make a a string rather than a list, you no longer need the join at all and you can just print a. – Post Rock Garf Hunter – 2019-02-28T21:45:49.700

4Invalid, it needs to be a full program or function, whereas you assume input is in x. – ASCII-only – 2019-03-01T04:32:49.180

63 – ASCII-only – 2019-03-01T04:35:49.840

@ASCII-only you no longer need the line break for the for loop. Thus 61

– akozi – 2019-03-01T13:09:13.920

3

Octave, 58 bytes

for k=1:(n=nnz(s=input(''))*2)-1
disp(s(1:min(k,n-k)))
end

Try it online!

Luis Mendo

Posted 2019-02-27T10:29:31.233

Reputation: 87 464

1I came up with essentially the same answer in MATLAB before I saw yours, but you get to take shortcuts in Octave with those compound assignments saving several bytes... I did briefly consider if any char maps to zero, such that nnz would miss it? – Wolfie – 2019-03-01T08:58:33.377

@Wolfie Somehow I assumed the input would not contain char(0), but you are right, it might be the case. I've asked for the OP if we can assume the standard ASCII range 32--127 – Luis Mendo – 2019-03-01T10:28:47.970

@Wolfie Confirmed: only printable ASCII – Luis Mendo – 2019-03-04T09:48:43.973

3

C# (Visual C# Interactive Compiler), 82 81 bytes

x=>{for(int l=x.Length,i=0;i<l*2-1;)WriteLine(x.Substring(0,l-Math.Abs(++i-l)));}

Try it online!

String as input and output to std

aloisdg moving to codidact.com

Posted 2019-02-27T10:29:31.233

Reputation: 1 767

3

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!

xnor

Posted 2019-02-27T10:29:31.233

Reputation: 115 687

3

C (gcc), 62 60 58 bytes

-2 bytes by using the write() approach of jaeyong-sung's answer.

i,d;f(char*s){for(d=1;write(1,s,i+=d-=!s[i]*2);puts(""));}

Try it online!

gastropner

Posted 2019-02-27T10:29:31.233

Reputation: 3 264

3

PHP, 79 bytes

function y($s,$l=1){echo$t=substr($s,0,$l)."
",$l<strlen($s)?y($s,$l+1).$t:'';}

Try it online!

Recursive in PHP as a function. Ungolfed version:

function y( $s, $l=1 ) {
    echo $t = substr( $s, 0, $l ) . "\n";
    if ( $l < strlen( $s ) ) {
        y( $s, $l+1 );
        echo $t;
    }
}

Call as y('String') outputs:

S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S

Or 69 bytes iterative with php -nF input as STDIN (basically a port of several other answers).

while(++$x<2*$l=strlen($s=$argn))echo substr($s,0,$l-abs($x-$l)),"
";

Try it online!

640KB

Posted 2019-02-27T10:29:31.233

Reputation: 7 149

3

[Assembly (nasm, x64, Linux)], 35 32 bytes

This is a function that takes a string (Pointer in RSI) and it's length (number in ebp), and outputs the required string to STDOUT.

EDI and EDX MUST be 0


ytc:
	;Actual setup
	inc ebp
	inc edi ;FD for STDOUT
	push rdi ;Value to add/subtract
	mov bl, 0Ah
.lp:
	add edx, [rsp] ;Str Length +- 1
	jz .end
	cmp edx, ebp
	jne .clp
	push -1
.clp:
	xchg [rsi+rdx-1], bl
	mov al, 1
	syscall
	xchg [rsi+rdx-1], bl
	jmp .lp
.end:
	ret

Try it online!

moonheart08

Posted 2019-02-27T10:29:31.233

Reputation: 693

3

BASH (+ GNU coreutils) 72 bytes

Takes input string from STDIN (one line)

read s;for i in `seq ${#s};seq $((${#s}-1)) -1 1`;do echo ${s:0:$i};done

example:

echo "Oh yeah yeah" | ./script.sh

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

Explanation:

# read string from STDIN into variable $s
read s

# `seq ${#s}` : sequence of numbers from 1 to length of string followed by
# `seq $((${#s}-1)) -1 1` : sequence of numbers from length-1 downto 1

# loop through sequence
for i in `seq ${#s};seq $((${#s}-1)) -1 1`;do

    # print substring of $s from position 0 to i
    echo ${s:0:$i}

# end of loop
done

Rene

Posted 2019-02-27T10:29:31.233

Reputation: 141

You can squish it down to 67 bytes... read s;for i in \seq ${#s};seq $[${#s}-1] -1 1`;{ echo ${s:0:$i};}` using some bash golf tricks. Example: https://ideone.com/Pw94LT

– roblogic – 2019-03-23T05:13:50.310

I golfed it down to 65 in bash using weird iterators! Here's my solution... tio.run

– roblogic – 2019-03-23T14:05:30.820

2

Brachylog, 8 bytes

a₀ᶠ;Lc.↔

Try it online!

Explanation

a₀ᶠ          Find all prefixes of the input
   ;Lc.      The output is that list of prefixes with something unknown appended at the end
      .↔     The output reversed is itself (i.e. it's a palindrome)

Fatalize

Posted 2019-02-27T10:29:31.233

Reputation: 32 976

2

R, 86 bytes

x=utf8ToInt(scan(,''))
for(i in c(y<-1:sum(x|1),rev(y)[-1]))cat(intToUtf8(x[1:i]),"
")

Try it online!

I'm learning more and more about better ways to manipulate strings in R, so I'm somewhat proud of this answer. The only part I don't like is the for loop portion, which I feel could definitely be golfed.

Sumner18

Posted 2019-02-27T10:29:31.233

Reputation: 1 334

1what about y<-seq(x)? – Droplet – 2019-02-27T17:10:38.120

2@Droplet you have to be quite careful about seq(x)! seq(x) behaves like seq_along(x) so long as x is not an integer or double of length 1. In that case, if x=c(65), for example, then seq(x) instead returns 1:x, which would not be the right behavior here. It's rather frustrating! – Giuseppe – 2019-02-27T18:09:30.740

You're right, I didn't think of the case when s was just one letter – Droplet – 2019-02-28T09:57:16.633

is the purpose of x=utf8ToInt(scan(,''))? – dylanjm – 2019-03-20T22:02:08.837

1

neat y<-seq(a=x) trick that somebody introduced (I forget who) try it online for -2 bytes!

– Giuseppe – 2019-04-04T22:14:55.833

2

MBASIC, 103 bytes

1 INPUT S$:N=1
2 PRINT LEFT$(S$,N):IF N<LEN(S$) THEN N=N+1:GOTO 2
3 N=N-1:PRINT LEFT$(S$,N):IF N>1 THEN 3

wooshinyobject

Posted 2019-02-27T10:29:31.233

Reputation: 171

2

Pyke, 6 bytes

BE 27 4F 5F 2B 58

Try it here!

        - input() (implicit)
.>      - prefixes(^) (1 byte)
  'O_   - ^[:-1], reversed(^)
     +  - [^]
      X - "\n".join(reversed(^))

Blue

Posted 2019-02-27T10:29:31.233

Reputation: 26 661

2

MathGolf, 7 bytes

£rñ{l<n

Try it online!

Explanation

£         length of array/string with pop
 r        range(0, n)
  ñ       pop(a), push palindromize(a) string/list/number
   {      start block or arbitrary length
    l     read string from input
     <    slice input string at index
      n   newline char

maxb

Posted 2019-02-27T10:29:31.233

Reputation: 5 754

2

><>,  44  41 bytes

i:0(?^l&}21.>ao&~
:o}1&:1-&) ?^
l&21.>~{~

Try it online!

Emigna

Posted 2019-02-27T10:29:31.233

Reputation: 50 798

2

VBA, 54 51 Bytes

(-3 bytes now that leading & trailing 0-character lines are confirmed as permitted)

x=Len([A1]):For i=-x To x:?Left([A1],x-abs(i)):Next

Just a simple loop from -Length to Length, omitting that many Absolute characters from the end each time

Input is cell A1 of the ActiveSheet. Output and Code are in the Immediate window

Chronocidal

Posted 2019-02-27T10:29:31.233

Reputation: 571

2

Kotlin, 62 bytes

{s->s.indices.map{s.take(it+1)}.let{it+it.reversed().drop(1)}}

Could probably be golfed more, but this is what I came up with.

Try it online!

snail_

Posted 2019-02-27T10:29:31.233

Reputation: 1 982

2

C, 78 bytes

#define f;printf("%.*s\n",i,d));
i;y(char*d){for(;i++<strlen(d)f for(i--;i--f}

Yoris

Posted 2019-02-27T10:29:31.233

Reputation: 31

173 – ASCII-only – 2019-04-04T05:31:42.633

2

Python 3, 79 72 bytes

Thanks Jo King for helping me save 7 bytes

I'm a bit late to this golf, but I was bored and didn't see a Python 3 one that gave a printable string and not a list. This isn't exactly very short but this is my first code golf post :)

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

Try it online!

Cello Coder

Posted 2019-02-27T10:29:31.233

Reputation: 61

Welcome to CGCC! Anonymous lambdas are acceptable submissions, so you can remove the f=. You can also change the if statement to a list selection ([i,len(x)-i][i>len(x)]) for a total of 72 bytes.

– Jo King – 2019-10-31T04:00:32.537

1

Julia, 40 bytes

s->(a=cumprod([s...]);[a;a[end-1:-1:1]])

Try it online!

Gets the first half by taking the cumulative product (* is string concatenation in Julia) of the array of characters, then adds this array to itself reversed minus the first element.

Thanks to @Kirill L. for 4 bytes.

Doorknob

Posted 2019-02-27T10:29:31.233

Reputation: 68 138

1

C# (Visual C# Interactive Compiler), 76 bytes

x=>{for(int i=0,s=1;s+i>0;s=i<x.Length?s:-s)WriteLine(x.Substring(0,i+=s));}

Try it online!

Using an iterative approach, as opposed to LINQ.

I did not realize until after I posted, but my answer is pretty similar to aloisdg's answer. Although they are different enough, I might just leave mine too :)

dana

Posted 2019-02-27T10:29:31.233

Reputation: 2 541

1Gald you posted it. I like it! – aloisdg moving to codidact.com – 2019-02-27T22:05:36.353

1

Python 2, 68 bytes

i,j=input(),''
j=[i[:x]for x in range(1,len(i))]
print j+[i]+j[::-1]

Try it online!

Longer than the other Python answers but just another way of doing it.

ElPedro

Posted 2019-02-27T10:29:31.233

Reputation: 5 301

1

Java (JDK), 86 bytes

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

Try it online!

Olivier Grégoire

Posted 2019-02-27T10:29:31.233

Reputation: 10 647

1

Python 2, 122 90 bytes

A worse solution of @xnor's

u=lambda n,s,b:s[:b-abs(n-b)]+'\n'+u(n+1,s,b)if n<2*b else""
def c(w):print(u(0,w,len(w)))

Try it online!

akozi

Posted 2019-02-27T10:29:31.233

Reputation: 551

1

APL(NARS), 24 char, 48 bytes

{⊃{w[⍵]}¨k,1↓⌽k←⍳¨⍳≢w←⍵}

test and how to use it:

  h←{⊃{w[⍵]}¨k,1↓⌽k←⍳¨⍳≢w←⍵}
        h ,'1'
1
  h '12'
1 
12
1 
  h '123'
1  
12 
123
12 
1  

comment: it would build one array of ranges [(1) (1 2) (1 2 3) ecc] and the code pass each of them to the function {w[⍵]}

RosLuP

Posted 2019-02-27T10:29:31.233

Reputation: 3 036

Use and a train, and return a vector of vectors to save: {(⊂¨(+,1↓⌽)⍳¨⍳≢⍵)⌷¨⊂⍵} Try it online!

– Adám – 2019-03-05T23:57:07.880

1

Wolfram Language (Mathematica), 63 bytes

(L=2StringLength@#;Do[Print@StringTake[#,Min[n,L-n]],{n,L-1}])&

Try it online!

Kai

Posted 2019-02-27T10:29:31.233

Reputation: 201

1

Factor, 77 bytes

: f ( s -- ) dup length [1,b] dup reverse 1 tail append [ head ] with map . ;

Try it online!

Galen Ivanov

Posted 2019-02-27T10:29:31.233

Reputation: 13 815

1

Wolfram Language (Mathematica), 100 bytes

StringJoin[#~Join~Reverse[#][[2;;]]&[Append[Take[#,i],"\n"]~Table~{i,1,Length[#]}&[Characters[#]]]]&

Try it online!

Rainer Glüge

Posted 2019-02-27T10:29:31.233

Reputation: 131

1

Nim, 83 76 bytes

let s=readline(stdin)
let l=len(s)
for a in 1..l*2-1:echo(s[0..<l-abs(a-l)])

Try it online!

My first time golfing in Nim. All inputs are welcome!

This is a port of my F# and C# answer.

  • -7 bytes by using the [a..<b] instead of substr() (source)

aloisdg moving to codidact.com

Posted 2019-02-27T10:29:31.233

Reputation: 1 767

1

Röda, 37 bytes

f s{{seq 1,#s-1;seq#s,1}|[s[:_],"
"]}

Try it online!

Explanation:

f s{ /* Function f(s) */
 {
  seq 1,#s-1; /* Push numbers 1..#s-1 to the stream (#s = length of s) */
  seq #s,1    /*   --..--     #s..1    --..-- */
 }|
 [       /* Print the following things for each _ in the stream: */
  s[:_], /*  Substring of s from 0 to _ */
  "
"        /*  Newline */
 ]
}

fergusq

Posted 2019-02-27T10:29:31.233

Reputation: 4 867

1

JavaScript (Node.js), 91 bytes

a=>{r=[];for(i=0;++i<a.length;)r.push(a.slice(0,i));return[...r,a,...r.reverse()].join`\n`}

Try it online!

Kamil Naja

Posted 2019-02-27T10:29:31.233

Reputation: 121

1

Pyth, 10 bytes

j+._zt_._z

Try it online!

j          # Join the final array with newlines and print
 +         # Join the two resulting arrays: 
  ._z      #   1. All prefixes of the input (z)
     t     #   2. Remove the first element (full word)
      _    #      of the reverse 
       ._z #      of all prefixes of the input (z)

Thanks to ASCII-only for helping get the bytes down!

GammaGames

Posted 2019-02-27T10:29:31.233

Reputation: 995

16 – ASCII-only – 2019-04-04T05:14:27.500

yours can also be 16 – ASCII-only – 2019-04-04T05:16:13.567

110 – ASCII-only – 2019-04-04T05:24:06.210

@ASCII-only The 16 ones have a trailing empty line, I didn't realize that was allowed so I had had added the Ik to fix that. That 10-byte entry is seriously impressive, why not submit it as a seperate answer? – GammaGames – 2019-04-04T14:09:14.977

>

  • i don't mind if you post it, 2. don't have time today, 3. it's 90% done by a builtin lol, i don't even know Pyth well
  • < – ASCII-only – 2019-04-04T14:11:58.663

    1

    Zsh, 60 bytes

    for c (${(s::Oa)1})(($#a))&&a=($c $c$^a $c)||a=$c
    <<<${(F)a}
    

    Try it online!

    for c (${(s::Oa)1})          # (s::) splits the first parameter, (Oa) reverses order
        (( $#a )) &&             # if $a is not empty, then
            a=($c $c$^a $c) ||   # ...set a to the current character, then the array with
                                 # the current character prepended to each element, else
            a=$c                 # ...set a to the current character
    <<< ${(F)a}                  # print a; (F) joins on newlines
    

    GammaFunction

    Posted 2019-02-27T10:29:31.233

    Reputation: 2 838

    1

    Python 2, 52 bytes

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

    Try it online!

    Returns a list of strings.

    Chas Brown

    Posted 2019-02-27T10:29:31.233

    Reputation: 8 959

    1

    CJam, 28 29 bytes

    l_,{_A)<oNo}fA_,{_A)~<oNo}fA;
    

    My first CJam answer, so this can probably be golfed quite a lot

    Edit: actually made it work correctly, at the cost of a byte

    Try it online!

    EdgyNerd

    Posted 2019-02-27T10:29:31.233

    Reputation: 1 106

    1

    Wolfram Language (Mathematica), 59 bytes

    Print/@Table[#~StringDrop~-Abs@i,{i,l=-StringLength@#,-l}]&
    

    Try it online!


    Taking input as a list of characters, and returning a list of character lists, 39 bytes:

    Table[#~Drop~-Abs@i,{i,l=-Tr[1^#],-l}]&
    

    Try it online!

    attinat

    Posted 2019-02-27T10:29:31.233

    Reputation: 3 495

    1

    Brain-Flak, 254 bytes

    <>(<()>)<>{({}(<()>))<>{({}<>)<>}{}((()()()()()){})(<()>)<>{({}(<()>))(({}<>)<{({}<>)<>}>{})(<()>)<>{({}<>)<>}{}}{}}<>{({}<>)(<()>)<>{({}<>)<>}{}((()()()()()){})(<()>)<>{({}(<()>))(({}<>)<{({}<>)<>}>{})(<()>)<>{({}<>)<>}{}}{}<>}<>{{}}<>{}{}{({}<>)<>}<>{}
    

    Try it online!

    Harder than expected (or maybe i'm just not very talented in Brain-Flak ^^)

    Explanation:

    <>(<()>)<>              push 0 on second stack
    
                            ### copy words with increasing letter count to second stack
    {                       while letters on stack
      ({}(<()>))            push 0 after first letter
      <>{                   move letters up to next 0 from second to first stack
        ({}<>)<>
      }
      {}                    pop 0
      ((()()()()()){})      append newline
      (<()>)                push new 0
      <>
                            ### append word from first to second stack
      {                     While letters on stack
        ({}(<()>))          push 0 after first letter
        (                   move letter on "third" stack for later use
          ({}<>)            move letter to other stack
          <{                move letters up to next 0 from second to first stack
            ({}<>)<>
          }>
          {}                pop 0
        )                   save letter from "third" stack
        (<()>)              push new 0
        <>{                 move letters up to next 0 from second to first stack
          ({}<>)<>
        }
        {}                  pop 0
      }
      {}                    pop 0
    }
    <>
    
                            ### copy words with decreasing letter count to second stack
    {                       while letters on second stack
      ({}<>)(<()>)<>        move letter and 0 on first stack
      {                     move letters up to next 0 from second to first stack
        ({}<>)<>
      }
      {}                    pop 0
      ((()()()()()){})      append newline
      (<()>)                push new 0
      <>
                            ### append word from first to second stack
      {                     While letters on stack
        ({}(<()>))          push 0 after first letter
        (                   move letter on "third" stack for later use
          ({}<>)            move letter to other stack
          <{                move letters up to next 0 from second to first stack
            ({}<>)<>
          }>
          {}                pop 0
        )                   save letter from "third" stack
        (<()>)              push new 0
        <>{                 move letters up to next 0 from second to first stack
          ({}<>)<>
        }
        {}                  pop 0
      }
      {}                    pop 0
      <>
    }
    
                            ### Tidy up
    <>
    {{}}                    delete input
    <>
    {}{}                    pop 0 and newline
    {({}<>)<>}              move everything from second to first stack
    <>
    {}                      pop newline
    

    Dorian

    Posted 2019-02-27T10:29:31.233

    Reputation: 1 521

    0

    Red, 78 bytes

    func[s][repeat n l: length? s[print copy/part s n]loop l[take/last s print s]]
    

    Try it online!

    Galen Ivanov

    Posted 2019-02-27T10:29:31.233

    Reputation: 13 815

    0

    x86 machine code (Linux), 53 bytes

    00000000: 89cf 31d2 4252 e814 0000 005a 803c 1100  ..1.BR.....Z.<..
    00000010: 75f2 4a52 e806 0000 005a 09d2 75f4 c36a  u.JR.....Z..u..j
    00000020: 015b 6a04 58cd 806a 0ab2 0189 e1b0 04cd  .[j.X..j........
    00000030: 805e 89f9 c3                             .^...
    

    Assembly:

    section .text
    	global func
    func:				;Main function with args: char* ecx
    					;Clear registers
    	mov edi, ecx			;push pointer to original string
    	xor edx, edx			;message length, start at 0
    	loop_a:				;Increasing length loop:
    		inc edx				;increment message length
    		push edx			;save message length
    		call print_text			;print string with newline
    		pop edx				;get message length
    		cmp byte [ecx + edx], 0		;If not at end of string:
    		jne loop_a			;continue looping
    	loop_b:				;Decreasing length loop:
    		dec edx				;decrement message length
    		push edx			;save message length
    		call print_text			;print string with newline
    		pop edx				;get message length
    		or edx, edx			;If edx != 0:
    		jne loop_b			;Continue loop
    	ret
    
    print_text:			;Function to print string (pointer in ecx) with newline:
    	push 1
    	pop ebx				;fd of stdout
    	push 4
    	pop eax				;syscall #4 (write)
    	int 0x80			;run syscall (msg is in ecx)
    	push 0xA			;push newline
    	mov dl, 1			;set message length to 1
    	mov ecx, esp			;set pointer for syscall to top of stack
    	mov al, 4			;syscall #4 (write)
    	int 0x80			;run syscall
    	pop esi				;reset stack pointer
    	mov ecx, edi			;get pointer to original string
    	ret
    

    Try it online!

    Logern

    Posted 2019-02-27T10:29:31.233

    Reputation: 845

    Tip: try and merge the increasing and decreasing length loops, like i did in my x64 answer. – moonheart08 – 2019-03-06T23:47:39.780

    0

    Java 8, 92 91 bytes

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

    Try it online!

    -1 byte by using a for loop instead of a while

    Benjamin Urquhart

    Posted 2019-02-27T10:29:31.233

    Reputation: 1 262

    87 bytes – ceilingcat – 2019-04-16T04:26:14.060

    0

    SAP ABAP (Unicode), 143 bytes

    FORM i USING s.DATA(w) = 2 * strlen( s ).WHILE w > 0.w = w - 1.IF w < strlen( s ).WRITE:/ s(w).ELSE.WRITE:/ s(sy-index).ENDIF.ENDWHILE.ENDFORM.
    

    Pretty straightforward subroutine. I'm using ABAP's substring access var+offset(length) and the system variable sy-index, which represents the index of the current loop. Other than that it's probably pretty self-explanatory, even though it's ABAP.


    SAP ABAP (Non-Unicode), 141 bytes

    FORM i USING s.DATA(w) = 2 * strlen( s ).WHILE w > 0.w = w - 1.IF w < strlen( s ).WRITE:/ s(w).ELSE.WRITE:/ s(sy(10)).ENDIF.ENDWHILE.ENDFORM.
    

    Saving two bytes here by accessing the index component of sy like a substring, despite it being an integer value. In Unicode systems, characters are obviously multi-byte values, therefore using offsets is not allowed in mixed-type structures like sy. However, in a non-Unicode (ASCII-based) system, both digits of a number and characters are represented as one byte each, and offsets are allowed for structures like sy.

    Conveniently index is the first 10-byte component of structure sy, so we don't need to use an offset. Otherwise we'd not be able to save anything here, as sy+x(10) is just as long as sy-index - or even longer if the offset was >= 10.


    Output of both programs is obviously the same, screenshot below.

    Output

    Maz

    Posted 2019-02-27T10:29:31.233

    Reputation: 191

    0

    Husk, 6 bytes

    S+o↔hḣ
    

    Try it online!

    Takes input as an argument.

    S      Apply the first argument to the third argument and to the second argument applied to the third argument:
     +     concatenation,
     o     the composition of
      ↔    reversal
      h    with removal of the last element,
     ḣ     every prefix of
           the input.
    

    ...I may need to not try to explain combinators in plain English.

    Unrelated String

    Posted 2019-02-27T10:29:31.233

    Reputation: 5 300

    I feel like there might be a way to shave a byte off this on account of this having used both S and o, but I'm not sure... – Unrelated String – 2019-03-20T06:12:44.353

    0

    T-SQL query, 119 bytes

    SELECT left(@,n)FROM(SELECT*,number/2+1n,len(@)k,number%2-.5m
    FROM spt_values)x
    WHERE type='P'and n+m<k
    ORDER BY(n-k)*m
    

    Try it online

    t-clausen.dk

    Posted 2019-02-27T10:29:31.233

    Reputation: 2 874

    0

    Gaia, 3 bytes

    …ṫṣ
    

    Try it online!

    As simple as it gets.

    …	| prefixes
     ṫ	| palindromize
      ṣ	| join with newlines
    

    Giuseppe

    Posted 2019-02-27T10:29:31.233

    Reputation: 21 077

    Bytes? These look like Unicode characters to me. – Mark Jeronimus – 2019-09-02T13:05:38.937

    @MarkJeronimus Gaia, like some other golfing languages, uses a custom code page so that each instruction is a single byte. – Giuseppe – 2019-09-02T19:04:25.390

    0

    PHP, 65 bytes

    for(;($n=$argn)!=$s.=$n[$i++];$b="$s
    $b")$a.="$s
    ";echo"$a$n
    $b";
    

    Try it online!

    Tests: Try it online!

    In a loop creates a word with one letter added to it towards input on each iteration until the word has one letter less than the input.

    For example if the input is "Hello" the word in first iteration is "H" and on third iteration is "Hel" and on last iteration is "Hell".

    This word is appended to $a and prepended to $b with a newline. At the end $a, input, a newline and $b are printed.

    Night2

    Posted 2019-02-27T10:29:31.233

    Reputation: 5 484

    0

    C (clang), 56 52 bytes

    i;f(*s,l){for(i=0;write(1,s,++i<l?i:l--);puts(""));}
    

    Try it online!

    -4 thanks to @ceilingcat

    Takes a string and its length as arguments.

    attinat

    Posted 2019-02-27T10:29:31.233

    Reputation: 3 495

    0

    GolfScript, 27 bytes

    .1/{0=1$?1$<}%n*.-1%@n+n\+\
    

    Try it online!

    user85052

    Posted 2019-02-27T10:29:31.233

    Reputation:

    0

    Fortran (GFortran), 79 bytes

    character(99)a
    read*,a
    k=len_trim(a)
    print('(a)'),(a(1:k-abs(i-k)),i=0,2*k)
    end
    

    Try it online!

    Fortran. Always good for string manipulation

    DeathIncarnate

    Posted 2019-02-27T10:29:31.233

    Reputation: 916

    0

    Keg, 37 bytes

    ?1&((⑻|⑩")(⑻|')⑹
    ,)⑺⑺((⑻|⑩")(⑻|')⑺
    ,)
    

    Try it online!

    I decided to try an interesting string shifting approach.

    Lyxal

    Posted 2019-02-27T10:29:31.233

    Reputation: 5 253

    0

    .+?, 28 bytes

    ((.+).(\n.+)*)
    \2\n\1\n\2
    $
    
    

    Thanks to JoKing for giving the original regex, which I then golfed a bit.

    Explanation

    ((.+).(\n.+)*)  The full pattern
    (            )  Makes group 1 the entire match, used in the replacement
     (.+).          Makes group 2 every character on the first line, except for the last character
          (\n.+)*   Makes it match the rest, so it all will get replaced
    
    \2\n\1\n\2      Replacement
    \2              Group 2 (first line except last character)
      \n            Newline
        \1          Group 1 (entire match)
          \n        Newline
            \2      Group 2 (first line except last character)
    
    $               This match always fails. Makes the first pair repeat until it doesn't match, which happens when the first line has less than 2 characters.
    
    

    Try it online! (The second command line argument is input)

    EdgyNerd

    Posted 2019-02-27T10:29:31.233

    Reputation: 1 106