19
\$\begingroup\$

The challenge is relatively simple, but will hopefully lead to some wonderfully creative answers. The task is to take a string as an input (via command line, function parameter etc.) and output/return a stringsploded version of it.

A stringsploded version of a string is its first letter followed by its first 2 letters, followed by its first 3 letters,... until you finally output the complete word.

You are guaranteed that the input will consist of printable ASCII characters and that the input will all be on one line (no new line characters).

Here are examples to clarify what stringsplosions are:

Input                 Output
==================================================================
"Code"       ---->   "CCoCodCode"
"name"       ---->   "nnanamname"
"harambe"    ---->   "hhaharharaharamharambharambe"
"sp aces?"   ---->   "sspsp sp asp acsp acesp acessp aces?"
"1234"       ---->   "1121231234"
"ss"         ---->   "sss"

This is code golf so shortest code wins + up votes for interesting uses of your respective language.

Good luck!

\$\endgroup\$
  • 8
    \$\begingroup\$ String challenges should usually specify the valid input characters, because it's not clear whether the input may contain a) non-letters, b) unprintable/control characters, c) null bytes, d) extended ASCII characters, e) Unicode characters beyond code point 256, (... f) combining marks, g) surrogates ...), all of which can arbitrarily complicate the challenge in many languages. And since your test cases only cover letters one might assume that that's your intended input range. \$\endgroup\$ – Martin Ender Sep 7 '16 at 14:13
  • 2
    \$\begingroup\$ You should add a test case where the first two characters are the same. \$\endgroup\$ – mbomb007 Sep 7 '16 at 14:26
  • 3
    \$\begingroup\$ As someone with a stutter, I'm OOfOffOffeOffenOffendOffendeOffended. \$\endgroup\$ – Shaun Wild Sep 7 '16 at 15:40
  • 2
    \$\begingroup\$ Alternate title: SStStrStriStrinStringStringsStringspStringsplStringsploStringsplodStringsplode \$\endgroup\$ – DJMcMayhem Sep 7 '16 at 17:38
  • 5
    \$\begingroup\$ Also related, near duplicate. \$\endgroup\$ – ETHproductions Sep 7 '16 at 22:43

43 Answers 43

20
\$\begingroup\$

gs2, 1 byte

x

  • gs2 takes input from STDIN, and pushes it to the stack as a string.
  • x is the prefixes built-in, returning a list of all prefixes of the argument, in ascending-length order.
  • The resulting list of strings is implicitly printed one-by-one, without a delimiter, when the program terminates.
\$\endgroup\$
  • \$\begingroup\$ Wow Speechless automagic wizardry \$\endgroup\$ – Rohan Jhunjhunwala Sep 7 '16 at 23:20
13
\$\begingroup\$

Jelly, 2 bytes

;\

Acculumate over concatenation gives all prefixes, which Jelly outputs to STDOUT without a delimiter. Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oh, cumulative reduce and reduce never seem to do what I expect. Surely a winner! Test cases \$\endgroup\$ – Jonathan Allan Sep 7 '16 at 14:36
  • \$\begingroup\$ @JonathanAllan Uh oh, Lynn did 1 byte :D \$\endgroup\$ – Yytsi Sep 7 '16 at 17:49
8
\$\begingroup\$

Retina, 4 bytes

.
$`

Expects the input to be terminated with a Windows-style \r\n newline (which seems fitting for a .NET-based programming language...).

This can be tested on Regex Storm (which uses \r\n newlines). Click the "Context" tab for the result.

This is essentially the same as Jordan's Ruby answer: it replaces each character in the input (including the \r but not the \n) with all the characters that came before it.

\$\endgroup\$
8
\$\begingroup\$

Java 7, 81 78 bytes

String g(String a){for(int i=a.length();i>0;)a=a.substring(0,--i)+a;return a;}

Straightforward method. Repeatedly prepends the shrinking prefix until it's done.

As a bonus, it should work for non-ASCII as well.

Sample:

Input:  ( ͡° ͜ʖ ͡°)
Output: (( ( ͡( ͡°( ͡° ( ͡° ͜( ͡° ͜ʖ( ͡° ͜ʖ ( ͡° ͜ʖ ͡( ͡° ͜ʖ ͡°( ͡° ͜ʖ ͡°)
\$\endgroup\$
  • \$\begingroup\$ You've beat me to it. Also, +1 I like the Lenny Face example. \$\endgroup\$ – Kevin Cruijssen Sep 7 '16 at 14:29
  • 2
    \$\begingroup\$ Haha, yes. I like to think of it as Lenny sliding into the room Kramer style when he hears something "appropriate". \$\endgroup\$ – Geobits Sep 7 '16 at 14:33
7
\$\begingroup\$

Jelly, 5 4 2 bytes

-2 bytes thanks to @Dennis

ḣJ

Test it at TryItOnline
Or all test cases, also at TryItOnline

How?

ḣJ - Main link takes one argument, e.g. "Code"
 J    - range(length(input)), e.g. [1,2,3,4]
ḣ    - head, x[:y] (implicit vectorization), e.g. "CCoCodCode"
\$\endgroup\$
  • 1
    \$\begingroup\$ ḣJ works too. \$\endgroup\$ – Dennis Sep 7 '16 at 15:13
  • \$\begingroup\$ @Dennis heh, forgot about J :) \$\endgroup\$ – Jonathan Allan Sep 7 '16 at 15:17
5
\$\begingroup\$

Brachylog, 11 5 bytes

:@[fc

Try it online!

Explanation

:@[f           Find all prefixes of the input
    c          Concatenate
\$\endgroup\$
5
\$\begingroup\$

05AB1E, 3 bytes

.pJ

Explanation

.p   # get list of prefixes of input
  J  # join as string

Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ Damn... I retire \$\endgroup\$ – gowrath Sep 7 '16 at 14:08
  • \$\begingroup\$ That .p idea was a goodun \$\endgroup\$ – Jonathan Allan Sep 7 '16 at 14:09
  • \$\begingroup\$ @JonathanAllan: A prefix command does come in handy now and then yeah :) \$\endgroup\$ – Emigna Sep 7 '16 at 14:09
  • \$\begingroup\$ Well.... Shoot. \$\endgroup\$ – user56309 Sep 7 '16 at 16:35
5
\$\begingroup\$

Ruby, 13 + 1 = 14 bytes

+1 byte for -p flag. Expects input on STDIN. Requires Windows-style line endings (\r\n).

gsub(/./){$`}

See it on eval.in (a few extra bytes since eval.in doesn't support command line flags): https://eval.in/637093

\$\endgroup\$
  • 1
    \$\begingroup\$ I think this only works with \r\n newlines. Otherwise, . doesn't have the last character to match (since it doesn't match \n). \$\endgroup\$ – Martin Ender Sep 7 '16 at 14:10
  • \$\begingroup\$ @MartinEnder I was actually just wondering why this works. That explains it. I forgot eval.in uses \r\n. I'll write a version that works with conventional newlines. \$\endgroup\$ – Jordan Sep 7 '16 at 14:13
  • 1
    \$\begingroup\$ I think assuming \r\n newlines is fine since that's the default on Windows (and in your online interpreter apparently). But you should mention it in the answer. \$\endgroup\$ – Martin Ender Sep 7 '16 at 14:14
  • \$\begingroup\$ I was going to post a Retina answer but it would now be straight port of yours, so if you want to post it yourself, it's simply . on the first line and $` on the second. \$\endgroup\$ – Martin Ender Sep 7 '16 at 14:15
  • \$\begingroup\$ @MartinEnder If you want to post it I won't take it personally. It's a pretty obvious solution so I don't feel proprietary about it. \$\endgroup\$ – Jordan Sep 7 '16 at 14:17
5
\$\begingroup\$

Javascript (ES6), 28 26 bytes

Recursively appends the shortened strings to the left of the final result:

f=s=>s&&f(s.slice(0,-1))+s

Examples

var
f=s=>s&&f(s.slice(0,-1))+s

console.log(f("Code"));     //  -->   "CCoCodCode"
console.log(f("name"));     //  -->   "nnanamname"
console.log(f("harambe"));  //  -->   "hhaharharaharamharambharambe"
console.log(f("sp aces?")); //  -->   "sspsp sp asp acsp acesp acessp aces?"
console.log(f("1234"));     //  -->   "1121231234"

\$\endgroup\$
  • \$\begingroup\$ Smart use of recursion +1 \$\endgroup\$ – Downgoat Sep 7 '16 at 14:50
5
\$\begingroup\$

MATL, 9 8 6 bytes

2 bytes saved thanks to @Luis

t&+Rf)

Try it Online!

Explanation

t       % Implicitly grab the input and duplicate
&+      % Broadcast and create a 2D matrix with all values > 0
R       % Grab the upper triangular portion (sets the lower triangular values to 0)
f       % Get the linear index for each value > 0
)       % Index into the original string (uses modular indexing)
        % Implicitly display the result
\$\endgroup\$
  • 1
    \$\begingroup\$ Cool Solution! (as MATL answers tend to be) \$\endgroup\$ – Emigna Sep 7 '16 at 14:11
4
\$\begingroup\$

JavaScript (ES6), 25 bytes

s=>s.replace(/./g,'$`$&')
\$\endgroup\$
3
\$\begingroup\$

Perl, 10 bytes

Includes +1 for -p

Run with the input on STDIN:

splode.pl <<< "Hello"

splode.pl

#!/usr/bin/perl -p
s/./$`/sg

This depends on the input being terminated by a newline. This 11 byte version does not need a final newline:

#!/usr/bin/perl -lp
s/.?/$`/g
\$\endgroup\$
3
\$\begingroup\$

CJam, 8 bytes

Here's 4 separate ways to get 8 bytes

l_,),\f<
l{1$\+}*
l{+_}*co
Ll{+_}/;

Credits to @MartinEnder for the last one. Online interpreter.

  • l_,),\f< creates the range [0 .. len(s)+1] then uses f< to slice for each number, producing all prefixes.

  • l{1$\+}* is a fold that duplicates the previous prefix and adds a char to it as it goes.

  • l{+_}*co is a bit weird - l{+_}* is also a fold but it produces the wrong prefixes, skipping the first and doubling the last (e.g. abcd -> ab/abc/abcd/abcd, slashes for clarity). We then use c to turn the last string into just its first character and output it with o, to get the first prefix.

  • Ll{+_}/; is a for-each loop that also duplicates the previous prefix and adds a char to it as it goes. We have an extra copy of the original string once the loop is over, which we pop with ;.

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

Haskell, 34 29 28 26 bytes

reverse=<<scanl(flip(:))[]
\$\endgroup\$
  • 1
    \$\begingroup\$ I'm just sad I can't use join.inits since neither of those are in the Prelude. \$\endgroup\$ – ballesta25 Sep 7 '16 at 17:30
  • \$\begingroup\$ @ballesta25 I know, FeelsBadMan. \$\endgroup\$ – ThreeFx Sep 7 '16 at 18:27
  • \$\begingroup\$ Hmm, concat.scanl(flip(:))[] $ "Code" -> "CoCdoCedoC". Each part (1st letter, 1st+2nd letter, ...) is in reverse. \$\endgroup\$ – nimi Sep 7 '16 at 20:53
  • \$\begingroup\$ @nimi is right. It needs to be reverse=<<scanl(flip(:))[] \$\endgroup\$ – Bergi Sep 8 '16 at 1:10
2
\$\begingroup\$

C, 49 bytes

i;f(char*n){for(i=0;i++<strlen(n);)write(1,n,i);}

Try on Ideone

\$\endgroup\$
  • \$\begingroup\$ You can golf it down to 41 bytes i;f(char*v){while(*(v+i))write(1,v,++i);} \$\endgroup\$ – cleblanc Sep 7 '16 at 15:05
2
\$\begingroup\$

Jellyfish, 5 bytes

P,\}I

Try it online!

Explanation

    I  # Read input.
  \}   # Get all prefixes.
 ,     # Flatten.
P      # Print.
\$\endgroup\$
2
\$\begingroup\$

V, 8 bytes

òÄ$xhòíî

Try it online!

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

C#, 91 87 84 83 bytes

void c(string n){var b="";for(int i=0;i<n.Length;)System.Console.Write(b+=n[i++]);}

Ungolfed:

void c(string n)
{
    var b = "";
    for (int i = 0; i < n.Length ; )
    {
        System.Console.Write(b+=n[i++]);
    }
}

Thank you Kevin Cruijssen.

\$\endgroup\$
  • 1
    \$\begingroup\$ +1 You can golf a few things, though. string b=""; can be var b=""; and i++ can be removed in the for-loop and added to the usage of i. So in total it becomes: void c(string n){var b="";for(int i=0;i<n.Length;){b+=n[i++];System.Console.Write(b);}} \$\endgroup\$ – Kevin Cruijssen Sep 7 '16 at 14:34
  • 1
    \$\begingroup\$ Ah, I can finally comment. Thanks for the suggestions! \$\endgroup\$ – Yodle Sep 7 '16 at 14:39
  • 1
    \$\begingroup\$ I've deleted my previous 84 bytes comment, because apparently it's possible to use b+= in the System.out.write.. So b=b+n[i++] can be changed to b+=n[i++] I wasn't sure if += is allowed there, but it is. Guess we both learned some things today. Sorry for making you edit all the time, and welcome to PPCG. :) Also, Tips for golfing in C# might be interesting to read through. \$\endgroup\$ – Kevin Cruijssen Sep 7 '16 at 14:44
  • \$\begingroup\$ Haha yeah. And for sure, I'll be checking a few tips of the languages I know. \$\endgroup\$ – Yodle Sep 7 '16 at 14:54
2
\$\begingroup\$

sed 41

h;:;G;s,.\n,\n,;h;s,\n.*,,;/./b;x;s,\n,,g
\$\endgroup\$
2
\$\begingroup\$

Sesos, 4 bytes

0000000: 8073ec 09                                         .s..

Try it online! Check Debug to see the generated SBIN code.

Sesos assembly

The binary file above has been generated by assembling the following SASM code.

    jmp, rwd 1, jnz
    fwd 1
    jmp, put, fwd 1, jnz
jnz
\$\endgroup\$
2
\$\begingroup\$

Python, 34 28 bytes

Here's my rough attempt with a recursive solution:

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

Ungolfed:

def f(s):
    if s: return f(s[:-1]) + s
    return ''

Try it here!

Thanks to @Dennis for -6 bytes.

\$\endgroup\$
  • 2
    \$\begingroup\$ I got ninja'd by recursives..... 300th time... \$\endgroup\$ – Erik the Outgolfer Sep 7 '16 at 15:59
  • 2
    \$\begingroup\$ f=lambda s:s and f(s[:-1])+s saves 6 bytes. \$\endgroup\$ – Dennis Sep 7 '16 at 16:25
  • \$\begingroup\$ Pretty sure you can remove the f= \$\endgroup\$ – Oliver Ni Sep 8 '16 at 1:32
  • \$\begingroup\$ @OliverNi How would I make the recursive call? \$\endgroup\$ – gowrath Sep 8 '16 at 9:05
2
\$\begingroup\$

CJam, 11 bytes

q{(L\+:Lo}h

Explanation:

q                   get input
 {       }h         do while 
  (L                get 1st character and variable L (initialized with "")
    \+              swap and concatenate them
      :Lo           store result in L and print it

Try it online

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

Dyalog APL, 3 bytes

∊,\

flatten the

,\ cumulative concatenation

TryAPL online!

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

Pyth, 3 bytes

s._

Explanation:

s   (s)um together 
 ._ all prefixes
\$\endgroup\$
2
\$\begingroup\$

R, 60 49 bytes

Not going to win any golf, but hopefully no shorter R answer is possible

cat(substring(s<-readline(),1,1:nchar(s)),sep="")

paste0(substring(s<-readLines(,1),1,1:nchar(s)),collapse="")

Thanks @MickyT

\$\endgroup\$
  • \$\begingroup\$ Well there's always cat(substring(s<-readline(),1,1:nchar(s)),sep="") :) \$\endgroup\$ – MickyT Sep 7 '16 at 20:00
1
\$\begingroup\$

Retina, 24 bytes

Well, I got destroyed by Martin, but here was my solution.

1m+`(.*).$
$1$.1$*¶$0
¶

Try it online

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

PowerShell v2+, 43 bytes

param($n)-join(1..$n.length|%{$n[0..--$_]})

Takes input $n, loops from 1 to $n.length, each iteration slicing $n from 0 up to one less than the current number -- done because .length is 1-indexed, while array slicing is 0-indexed. Each iteration places characters on the pipeline, those are encapsulated in parens and -joined together into one string. Output is implicit.

PS C:\Tools\Scripts\golfing> .\stringsplode-the-string.ps1 'PPCG'
PPPPPCPPCG

Alternatively, using Jordan's Ruby submission as a basis, you can get to the following for 22 bytes

$input-replace'.','$`'

This feels kinda cheaty, though, since you'd have to explicitly insert a newline into the string that you're piping in, or otherwise do a Get-Content or something out of a file that pulls the newlines with it. Valid, but not really common.

PS C:\Tools\Scripts\golfing> 'PPCG
' | .\stringsplode-the-string.ps1 $_
PPPPPCPPCG
\$\endgroup\$
  • \$\begingroup\$ If I pipe a string into another program, it gets the \r\n at the end automatically. Looks like PowerShell scripts are treated differently in that regard? \$\endgroup\$ – Martin Ender Sep 7 '16 at 14:31
  • \$\begingroup\$ @MartinEnder Yeah. I'm not sure if it's because piping in PowerShell is handled differently than piping in other shells, or because the items passed between the pipe are literal objects and there's no \r\n at the end of the literal string. Probably a combination. \$\endgroup\$ – AdmBorkBork Sep 7 '16 at 14:33
1
\$\begingroup\$

C 71 67 Bytes

k;f(v){char*m,*n=v;while(*n++)for(k=0,m=v;k<n-v;k++)putchar(*m++);}
\$\endgroup\$
1
\$\begingroup\$

Gema, 16 characters

?=@append{s;?}$s

Sample run:

bash-4.3$ echo -n 'sp aces?' | gema '?=@append{s;?}$s'
sspsp sp asp acsp acesp acessp aces?
\$\endgroup\$
1
\$\begingroup\$

Python 3, 47 bytes

Thanks to @deustice

lambda s:''.join(s[:i]for i in range(len(s)+1))

Ideone it!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can take out the 0, just s[:i] should work \$\endgroup\$ – deustice Sep 7 '16 at 15:12
  • \$\begingroup\$ @deustice Oh, of course, thanks! \$\endgroup\$ – Beta Decay Sep 7 '16 at 17:03

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