40
\$\begingroup\$

Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once. The second character is shown twice. The third character is shown thrice, and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A aaannnnddddd BBBBBBB

Shortest bytes wins :)

\$\endgroup\$
8
  • 2
    \$\begingroup\$ That seems to disagree with "no support for whitespace is needed, other than the space character". Should the output be the same as the input then? (Two one letter words?) Also note we have a nice place called the Sandbox where you can put challenges for people to give you feedback before posting them. \$\endgroup\$ Commented Jun 20, 2016 at 19:50
  • \$\begingroup\$ FryAmTheEggman your assumption is valid. @TimmyD I realize where I was unclear, you may end up with strings separated my multiple spaces, as seen in the example FryAmTheEggman posted. \$\endgroup\$ Commented Jun 20, 2016 at 19:52
  • \$\begingroup\$ I'm assuming that the shortest code wins? ;) \$\endgroup\$
    – Adnan
    Commented Jun 20, 2016 at 19:54
  • \$\begingroup\$ @Adnan Yep, though I'm not sure if I should mark the answer with the shorted program as accepted, as certain languages are made for golfing purposes unlike others. \$\endgroup\$ Commented Jun 20, 2016 at 19:56
  • 2
    \$\begingroup\$ Related: 1, 2 \$\endgroup\$
    – Sp3000
    Commented Jun 21, 2016 at 3:36

67 Answers 67

36
\$\begingroup\$

Jelly, 3 bytes

Code:

ĖP€

Explanation:

Ė     # Enumerate.
 P€   # Product of each.
      # Implicit joining of everything.

Uses the Jelly encoding. Try it online!.

\$\endgroup\$
3
  • 19
    \$\begingroup\$ Nice abuse of the fact that Python's * does string multiplication. That's not really intended, but it works. \$\endgroup\$
    – Dennis
    Commented Jun 20, 2016 at 20:56
  • 1
    \$\begingroup\$ @Dennis: which *? There's no such thing in the whole answer. \$\endgroup\$ Commented Jun 22, 2016 at 6:08
  • 14
    \$\begingroup\$ @Thomas: Jelly is written in Python, and the Jelly P command calculates product behind the scenes using the Python * operator. This post is abusing the leaky abstraction of the underlying code actually being in Python, so doing a P (product) command on a string works as expected. \$\endgroup\$
    – mellamokb
    Commented Jun 22, 2016 at 13:57
17
\$\begingroup\$

J, 4 bytes

#~#\

Usage

   f =: #~#\
   f 'Why'
Whhyyy
   f 'SKype'
SKKyyyppppeeeee
   f 'LobbY'
LoobbbbbbbYYYYY
   f 'A and B'
A  aaannnnddddd      BBBBBBB

Explanation

#~#\  Input: s
  #\  Computes the length of each prefix of s
      This forms the range [1, 2, ..., len(s)]
#~    For each value in the range, copy the character at the
      corresponding index that many times
      Return the created string
\$\endgroup\$
13
\$\begingroup\$

Brainfuck, 15 bytes

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

Pretty straightforward implementation, shifting the memory space by 1 for each input char. Requires an interpreter that gives 0 on EOF, and 32-bit/arbitrary precision cells for inputs longer than 255 chars.

Try it online! (Note: TIO uses 8-bit cells)

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Also, I think that this doesn't work for strings longer than 255 characters. \$\endgroup\$ Commented Jun 22, 2016 at 10:07
  • \$\begingroup\$ @IsmaelMiguel That would depend on whether the interpreter in question has arbitrary precision integers or not (but indeed, for most implementations, it would cap at 255) \$\endgroup\$
    – Sp3000
    Commented Jun 22, 2016 at 10:13
  • \$\begingroup\$ The convention is to use 8-bits. Which is 1 character. But some may indeed implement with 32-bit numbers. Since you specify you need that EOF be 0 (which is a compiler/interpreter-specific behaviour), it should be noted that for strings longer than 255 characters, you need a compiler/interpreter with 32-bit cells. I just though that it should be added to the answer, since it is also a compiler/interpreter-specific behaviour. \$\endgroup\$ Commented Jun 22, 2016 at 10:23
  • 1
    \$\begingroup\$ @IsmaelMiguel Sure, noted. \$\endgroup\$
    – Sp3000
    Commented Jun 22, 2016 at 10:35
10
\$\begingroup\$

Haskell, 29 bytes

concat.zipWith replicate[1..]

Usage example: concat.zipWith replicate[1..] $ "SKype" -> "SKKyyyppppeeeee".

replicate n c makes n copies of c and concat makes a single list out of all the sublists.

\$\endgroup\$
10
  • \$\begingroup\$ id=<< is a nice touch. :) \$\endgroup\$
    – sudee
    Commented Jun 20, 2016 at 20:04
  • \$\begingroup\$ I just wanted to try it, but assigning f = id=<<zipWith replicate[1..] (in a file) did result in an ugly error, can you tell what I'm doing wrong? \$\endgroup\$
    – flawr
    Commented Jun 20, 2016 at 20:37
  • \$\begingroup\$ Shouldn't it be possible to assign this (unnamed, right?) function to a name, such that we can use it as a function? I mean if it is a function, then (id=<<zipWith replicate[1..] ) "SKype" should still work? Otherwise I would consider it as a snippet. The full program you provided does have "SKype" hardcoded. \$\endgroup\$
    – flawr
    Commented Jun 20, 2016 at 20:42
  • 2
    \$\begingroup\$ I'd say if you cannot use it like any other function, it is not a function. E.g. :t does not regard id=<<zipWith replicate[1..] as a function (it just throws an error) however (id=<<).zipWith replicate[1..] is considered as a function. I'd say the first one is just a snipped, that just works if you hardcode the input, but the second one that you just postet is a function (and :t agrees), would you agree on that? \$\endgroup\$
    – flawr
    Commented Jun 20, 2016 at 20:55
  • 1
    \$\begingroup\$ @flawr: there are also values (e.g. :t "test") and kinds. \$\endgroup\$
    – nimi
    Commented Jun 20, 2016 at 21:27
9
\$\begingroup\$

Java, 158 121 bytes

Saved a whopping 37 bytes thanks to Kevin Cruijssen!

interface a{static void main(String[]A){int b=0,B;for(char c:A[0].toCharArray())for(B=b+++2;--B>0;)System.out.print(c);}}

As a bonus, this program can handle all Unicode characters in the existence, including the control characters located at the very end of Basic Multilingual Plane.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ Huh, this is very short for a Java code. \$\endgroup\$
    – ave
    Commented Jun 20, 2016 at 23:47
  • 1
    \$\begingroup\$ You can shorten it by 1 byte by replacing for(int C=c+1;C>0;C--) with for(int C=c+2;--C>0;) \$\endgroup\$ Commented Jun 21, 2016 at 6:50
  • 2
    \$\begingroup\$ Or even shorter (121 bytes): interface a{static void main(String[]A){int x=0,i;for(char c:A[0].toCharArray())for(i=x+++2;--i>0;)System.out.print(c);}} \$\endgroup\$ Commented Jun 21, 2016 at 6:57
  • \$\begingroup\$ Well, just make it a lambda or a method \$\endgroup\$
    – Leaky Nun
    Commented Jun 21, 2016 at 13:22
  • 2
    \$\begingroup\$ Wow, using an interface for the default public methods. That's smart. \$\endgroup\$
    – Justin
    Commented Jun 22, 2016 at 0:45
8
\$\begingroup\$

Perl, 16 bytes

s/./$&x$+[0]/ge

+1 byte for the -p flag.

s/./        /    find every character
             g   globally
              e  and replace with the eval'd result of
    $&           the matched string
      x          repeated
       $+[0]     by the index of the character after the match
\$\endgroup\$
8
\$\begingroup\$

Python, 39 bytes

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

Test it on Ideone.

\$\endgroup\$
7
\$\begingroup\$

CJam, 9 8 7 bytes

Thanks to jimmy23013 for saving 1 byte.

Sl+eee~

Test it here.

Explanation

Using the LobbY example:

                                      Stack:
S    e# Push space.                   [" "]
l    e# Read input.                   [" " "LobbY"]
+    e# Append.                       [" LobbY"]
ee   e# Enumerate.                    [[[0 ' ] [1 'L] [2 'o] [3 'b] [4 'b] [5 'Y]]]
e~   e# Run-length decode.            ["LoobbbbbbbYYYYY"]
\$\endgroup\$
0
6
\$\begingroup\$

MATLAB, 45 bytes

g=@(m)sort(m(m>0));@(s)s(g(hankel(1:nnz(s))))

Explanation: The key is hankel, which produces a Hankel matrix of a given vector. From this matrix, we can extract a vector of indices, which defines which character of the string is at which position in the output. E.g. hankel(1:4) produces following matrix:

 1  2  3  4
 2  3  4  0
 3  4  0  0
 4  0  0  0

From this matrix we can extrac the vector 1,2,2,3,3,3,4,4,4,4,4. This vector allows us to output the first character of the string once, the second one twice e.t.c.

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

Javascript ES6, 39 bytes

x=>x.replace(/./g,(y,i)=>y+y.repeat(i))

Same length, but more fun:

x=>x.replace(i=/./g,y=>y.repeat(i=-~i))

Snippet demo:

f= x=>x.replace(/./g,(y,i)=>y+y.repeat(i))
run.onclick=_=>output.textContent=f(input.value)
<input id="input" value="SKype">
<button id="run">Go</button>
<pre id="output"></pre>

\$\endgroup\$
6
  • \$\begingroup\$ Small error, the program does not support spaces, which is required as a submission (check the OP). \$\endgroup\$ Commented Jun 20, 2016 at 21:59
  • \$\begingroup\$ @MarDev I changed the snippet to use <pre> instead of <div>, that should help. \$\endgroup\$
    – Neil
    Commented Jun 20, 2016 at 22:55
  • 1
    \$\begingroup\$ @Neil Ah, so the result was correctly computed, but the output was rendered incorrectly by the HTML. Forgot that <div> does that. \$\endgroup\$ Commented Jun 21, 2016 at 0:43
  • \$\begingroup\$ ..."and output the result" \$\endgroup\$
    – spender
    Commented Jun 23, 2016 at 1:30
  • 1
    \$\begingroup\$ @spender returning is a valid form of output for functions \$\endgroup\$
    – cat
    Commented Jun 23, 2016 at 15:15
5
\$\begingroup\$

APL (dzaima/APL), 6 5 bytes

⍳∘≢⌿⊢

Try it online!

⍳∘≢ enumeration of the argument... (indices of its length)
replicates the elements of...
the unmodified argument

\$\endgroup\$
7
  • \$\begingroup\$ link to interpreter? \$\endgroup\$
    – cat
    Commented Jun 23, 2016 at 15:14
  • \$\begingroup\$ @cat See edit (in header). \$\endgroup\$
    – Adám
    Commented Jun 23, 2016 at 15:31
  • \$\begingroup\$ @cat What was your edit? \$\endgroup\$
    – Adám
    Commented Jun 23, 2016 at 15:48
  • \$\begingroup\$ Identical to yours down to the character, because I googled it myself and my edit took 10 minutes to submit \$\endgroup\$
    – cat
    Commented Jun 23, 2016 at 16:31
  • \$\begingroup\$ Also, in which codepage is this 6 bytes? \$\endgroup\$
    – cat
    Commented Jun 23, 2016 at 18:12
4
\$\begingroup\$

APL (8)

{⍵/⍨⍳⍴⍵}

I.e.:

      {⍵/⍨⍳⍴⍵} ¨  'Why' 'SKype' 'LobbY'
┌──────┬───────────────┬───────────────┐
│Whhyyy│SKKyyyppppeeeee│LoobbbbbbbYYYYY│
└──────┴───────────────┴───────────────┘

Explanation:

  • ⍴⍵: length of given vector
  • : numbers 1..N
  • ⍵/⍨: replicate each element in N times.
\$\endgroup\$
4
\$\begingroup\$

Brachylog, 13 bytes

:ImC,0:Ie,Cw\

This prints the result to STDOUT.

Explanation

This is a good example of exploiting backtracking to loop.

:ImC            C is the Ith character of the Input
    ,
     0:Ie       Unify an implicit variable with an integer between 0 and I
         ,
          Cw    Write C to STDOUT
            \   False, trigger backtracking. It will go back to 0:Ie and unify the implicit
                variable with another integer, until all integers were used. After that, it
                will backtrack to :ImC and unify I and C with the next character.
\$\endgroup\$
4
\$\begingroup\$

Javascript ES6, 42 41 bytes

s=>[,...s].map((e,i)=>e.repeat(i)).join``

Example runs:

f=s=>[,...s].map((e,i)=>e.repeat(i)).join``

f("Why")   => "Whhyyy"
f("SKype") => "SKKyyyppppeeeee"
f("LobbY") => "LoobbbbbbbYYYYY"
\$\endgroup\$
3
  • \$\begingroup\$ Same length: s=>[...s].reduce((a,b,i)=>a+b.repeat(i+1)) \$\endgroup\$ Commented Jun 21, 2016 at 12:27
  • 2
    \$\begingroup\$ -1 byte: s=>[,...s].map((e,i)=>e.repeat(i)).join`` \$\endgroup\$
    – nderscore
    Commented Jun 21, 2016 at 16:14
  • \$\begingroup\$ @nderscore Aha, thats clever, thanks! \$\endgroup\$
    – Dendrobium
    Commented Jun 21, 2016 at 16:28
4
\$\begingroup\$

R, 83 50 bytes

-23 Thanks to Giuseppe, though he used essentially an entire new method altogether

function(s)intToUtf8(rep(utf8ToInt(s),1:nchar(s)))

My original post:

function(s){r="";for(i in 1:nchar(s))r=paste0(r,strrep(el(strsplit(s,""))[i],i));r}

Try it online!

I feel like there's definitely a better way to do this, but with my new knowledge of a few functions in R, this is my approach.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Not a golfing tip, but your code link output was messed up. Here \$\endgroup\$
    – Robert S.
    Commented Aug 31, 2018 at 19:28
  • \$\begingroup\$ Ah, I see. I'm new to TIO, so I didn't quite understand the header/footer portions. Thank You! \$\endgroup\$
    – Sumner18
    Commented Aug 31, 2018 at 19:37
  • \$\begingroup\$ Using scan saves 1 byte! \$\endgroup\$
    – Robert S.
    Commented Aug 31, 2018 at 20:21
  • 1
    \$\begingroup\$ Very nice! However, using rep and the argument collapse="" to paste is shorter, and utf8ToInt is shorter still! TIO \$\endgroup\$
    – Giuseppe
    Commented Aug 31, 2018 at 20:36
  • \$\begingroup\$ Using \(x) instead of function(x) will save a few bytes \$\endgroup\$
    – lebatsnok
    Commented Aug 23, 2022 at 16:40
3
\$\begingroup\$

PowerShell v2+, 36 bytes

-join([char[]]$args[0]|%{"$_"*++$i})

Takes input $args[0], explicitly casts it as a char array, sends that into a loop |%{...}. Each iteration we take the current letter/character "$_" and use the * overloaded operator to concatenate the string pre-incremented $i times. The result of each loop iteration is encapsulated in parens to form an array and then -joined together to form a string. That string is left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 Why
Whhyyy

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 SKype
SKKyyyppppeeeee

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 LobbY
LoobbbbbbbYYYYY

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 'a b'
a  bbb
\$\endgroup\$
3
\$\begingroup\$

MATLAB, 23 bytes

@(x)repelem(x,1:nnz(x))

Creates an anonymous function ans that can be called using ans('stringtoelacticize')

\$\endgroup\$
2
  • \$\begingroup\$ What version are you using? Cannot find repelem in my (relatively old) version =( \$\endgroup\$
    – flawr
    Commented Jun 21, 2016 at 9:12
  • 1
    \$\begingroup\$ @flawr repelem was introduced in R2015a \$\endgroup\$
    – Luis Mendo
    Commented Jun 21, 2016 at 14:05
3
\$\begingroup\$

K/Kona, 14 bytes

{,/(1+!#x)#'x}

Usage:

k){,/(1+!#x)#'x}"A and B"
"A  aaannnnddddd      BBBBBBB"
\$\endgroup\$
3
\$\begingroup\$

Perl 6,  22 20  19 bytes

{S:g/(.)/{$0 x$/.to}/}
{S:g[(.)]=$0 x$/.to}
{[~] .comb Zx 1..*}

Explanation:

{          # implicit parameter $_
  [~]      # string concatenate the following list
    .comb  # the NFG characters from $_
    Z[x]   # zip combined using the string repetition operator
    1 .. * # 1 to infinity
}
\$\endgroup\$
3
  • \$\begingroup\$ What are the first two lines for? \$\endgroup\$
    – Mark Reed
    Commented Jan 28, 2023 at 15:28
  • \$\begingroup\$ @MarkReed Those are the first two versions I came up with \$\endgroup\$ Commented Jan 29, 2023 at 20:34
  • \$\begingroup\$ Oh! the 22- and 20-char solutions listed in the title. I'm dumb. :) \$\endgroup\$
    – Mark Reed
    Commented Jan 29, 2023 at 23:32
3
\$\begingroup\$

VBA, 75 bytes

Function e(s):For a=1 To Len(s):e=e &String(a,Mid(s,a,1)):Next:End Function

Call as e.g. a user function in a spreadsheet.

=e(A1)

┌─────────┬───────────────┐
│   SKype │SKKyyyppppeeeee│
└─────────┴───────────────┘

It truncates if you feed it its own output a few times :-).

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to the site! =) \$\endgroup\$
    – DJMcMayhem
    Commented Jun 21, 2016 at 7:28
3
\$\begingroup\$

Julia, 32 bytes

!s=join(split(s[k=1:end],"").^k)

Unlike Dennis's solution, this is not recursive. split with argument "" separates the string into an array of strings of length 1. The [k=1:end] is a trick to create a range from 1 to the number of characters in the string, and this range is used to concatenate n copies of the n-th character. join then recombines the array of strings into a single string, in order.

Usage example: !"SKype"

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

PHP, 68 bytes

<?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);
\$\endgroup\$
2
  • \$\begingroup\$ Hi, and welcome to PPCG! Nice first post! \$\endgroup\$
    – Riker
    Commented Jun 21, 2016 at 14:41
  • \$\begingroup\$ You can get it down to 47 bytes: for(;$a=$argv[1][$i++];)echo str_repeat($a,$i);. \$\endgroup\$ Commented Jun 21, 2016 at 19:59
3
\$\begingroup\$

Retina, 22 bytes

Byte count assumes ISO 8859-1 encoding.

.
$&$.`$*·
+`(.)·
$1$1

Try it online!

Basically, we insert the right amount of · as placeholders between the characters (since these extended ASCII characters can't appear in the input), then fill them up with the adjacent character in the second stage.

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

05AB1E, 2 bytes

ƶJ

Try it online or verify all test cases.

Explanation:

ƶ   # Multiply each character in the (implicit) input-string by its 1-based index
 J  # Join the list of substrings together to a single string
    # (after which the result is output implicitly)
\$\endgroup\$
3
\$\begingroup\$

Vyxal s, 2 bytes

Þż

Try it online, or see a 3 byte flagless version

\$\endgroup\$
2
  • \$\begingroup\$ 3, 2 with the s flag \$\endgroup\$
    – emanresu A
    Commented Aug 21, 2022 at 8:18
  • \$\begingroup\$ Ah, thought so. I saw that and wondered if that was it but I wasn't sure, thanks. \$\endgroup\$ Commented Aug 21, 2022 at 9:04
3
\$\begingroup\$

BQN, 9 8 bytes

⊢/˜1+↕∘≠

Anonymous tacit function. Try it at BQN online!

Explanation

⊢/˜1+↕∘≠
       ≠  Length of argument
     ↕∘   Range
   1+     Add 1 to each, making it an inclusive range from 1 to the length
 /˜       Replicate that many times the elements of
⊢         The original input
\$\endgroup\$
3
\$\begingroup\$

><> (Fish), 33 bytes

1:i:0(?^$:?v~~1+00.
.!02o:$;!-1<|

Try the animated version

enter image description here

Basically if the counter is 0 skip to the second :, otherwise the first :. Properly adjust the counters.

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

Actually, 7 bytes

' +ñ♂πΣ

Try it online!

Explanation:

' +ñ♂πΣ
' +      prepend a space
   ñ     enumerate ("abc" -> [[0, 'a'], [1, 'b'], [2, 'c']])
    ♂π   map: for each character, repeat it n times
      Σ  concatenate
\$\endgroup\$
2
\$\begingroup\$

Pyth - 5 bytes

1 byte saved thanks to @FryAmTheEggman.

s*VSl

Test Suite.

\$\endgroup\$
1
  • \$\begingroup\$ @FryAmTheEggman ah, nice one. \$\endgroup\$
    – Maltysen
    Commented Jun 20, 2016 at 20:05
2
\$\begingroup\$

Python 3, 48 47 bytes

Thanks to mego for saving a byte with the -~i trick.

lambda s:''.join(c*-~i for i,c in enumerate(s))

This is mostly self-explanatory. One thing for those not versed in Python: The * operator is overloaded to act like Perl's x operator, repeating its string argument the number of times specified by its numeric argument. E.g. 'foo' * 3 == 'foofoofoo'

\$\endgroup\$
2
  • \$\begingroup\$ c*-~i is shorter than c*(i+1). \$\endgroup\$
    – user45941
    Commented Jun 20, 2016 at 20:07
  • \$\begingroup\$ know your language... there is an offset argument to enumerate :) - still 47 bytes though: lambda s:''.join(c*i for i,c in enumerate(s,1)) \$\endgroup\$
    – movatica
    Commented Feb 17, 2021 at 15:26

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.