Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

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

share|improve this question
2  
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. – FryAmTheEggman yesterday
    
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. – Mar Dev yesterday
    
I'm assuming that the shortest code wins? ;) – Adnan yesterday
    
@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. – Mar Dev yesterday
    
And here I was ready to be clever and start making strings more expensive as more of them were allocated... – J... 20 hours ago

41 Answers 41

up vote 18 down vote accepted

Jelly, 3 bytes

Code:

ĖP€

Explanation:

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

Uses the Jelly encoding. Try it online!.

share|improve this answer
8  
Nice abuse of the fact that Python's * does string multiplication. That's not really intended, but it works. – Dennis yesterday

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
share|improve this answer

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.

share|improve this answer
    
id=<< is a nice touch. :) – sudee yesterday
    
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? – flawr yesterday
    
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. – flawr yesterday
    
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? – flawr yesterday
    
Ok, great! If you disagree with my "definition", I think we should start a meta post for clearing this up. In the mean time I'm trying to find some other haskellians for their opinion on this, as this is just my view. – flawr yesterday

Brainfuck, 15 bytes

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

Pretty straightforward implementation, shifting the memory space by 1 for each input char. Requires an interpreter that gives 0 on EOF.

Try it online!

share|improve this answer

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"]
share|improve this answer
1  
e~ for ::*. – jimmy23013 22 hours ago
    
@jimmy23013 Oh duh, I completely ignored that because so far whenever I wanted to combine ee and e~ the pairs were the wrong way around. Thank you. :) – Martin Ender 13 hours ago

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.

share|improve this answer
    
Huh, this is very short for a Java code. – ardaozkal 21 hours ago
    
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;) – Kevin Cruijssen 14 hours ago
1  
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);}} – Kevin Cruijssen 14 hours ago
    
Well, just make it a lambda or a method – Leaky Nun 8 hours ago

APL (8)

{⍵/⍨⍳⍴⍵}

I.e.:

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

Explanation:

  • ⍴⍵: length of given vector
  • : numbers 1..N
  • ⍵/⍨: replicate each element in N times.
share|improve this answer

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.

share|improve this answer

MATLAB, 23 bytes

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

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

share|improve this answer
    
What version are you using? Cannot find repelem in my (relatively old) version =( – flawr 12 hours ago
1  
@flawr repelem was introduced in R2015a – Luis Mendo 7 hours ago

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
share|improve this answer

Python, 39 bytes

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

Test it on Ideone.

share|improve this answer

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'

share|improve this answer
    
c*-~i is shorter than c*(i+1). – Mego yesterday

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.
share|improve this answer

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>

share|improve this answer
    
Small error, the program does not support spaces, which is required as a submission (check the OP). – Mar Dev 23 hours ago
    
@MarDev I changed the snippet to use <pre> instead of <div>, that should help. – Neil 22 hours ago
    
@Neil Ah, so the result was correctly computed, but the output was rendered incorrectly by the HTML. Forgot that <div> does that. – Mar Dev 20 hours ago
    
Thanks for the edit @Neil – nderscore 6 hours ago

Python, 40 bytes

f=lambda s,i=1:s and s[0]*i+f(s[1:],i+1)
share|improve this answer

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
}
share|improve this answer

LINQPad w/ C#, 82 bytes

void m(string s){Console.Write(s.SelectMany((x,i)=>new string(x,++i)).ToArray());}

Single output operation.

share|improve this answer
    
@MartinEnder using System; & using System.Linq; are not necessary in LINQPad. – Søren D. Ptæus 9 hours ago
    
Oh, I wasn't aware of that. – Martin Ender 9 hours ago

PHP, 68 bytes

<?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);
share|improve this answer
    
Hi, and welcome to PPCG! Nice first post! – Eᴀsᴛᴇʀʟʏ Iʀᴋ 6 hours ago
    
You can get it down to 47 bytes: for(;$a=$argv[1][$i++];)echo str_repeat($a,$i);. – insertusernamehere 1 hour ago

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
share|improve this answer

05AB1E, 6 bytes

vN>Fy?

Explained

v       # for each char in string
 N>F    # index+1 number of times do
    y?  # print current char

Try it online

share|improve this answer
1  
This one looks like it has a question :D – dorukayhan yesterday

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
share|improve this answer

Pyth - 5 bytes

1 byte saved thanks to @FryAmTheEggman.

s*VSl

Test Suite.

share|improve this answer
    
@FryAmTheEggman ah, nice one. – Maltysen yesterday

C#, 81 Bytes

void f(string s){for(int i=0;i<s.Length;i++)Console.Write(new String(s[i],i+1));}
share|improve this answer
    
you can save 1 byte by changing to a foreach loop, e.g. foreach(var a in s)Console.Write(new C(a,1*i++)); – Abbath 22 hours ago
    
but if its a foreach we don't have the i variable so you'd need to declare it. – ScifiDeath 11 hours ago
    
It seems you're missing a using System or a System. in front of the Console. – Martin Ender 9 hours ago
    
@ScifiDeath That's true - but the end result is still one byte shorter. Sorry for omitting it and causing confusion int i=1; – Abbath 7 hours ago

MATL, 5 bytes

tn:Y"

Try it Online

Explanation

    % Implictly grab input as a string
tn  % Duplicate and compute the length (N)
:   % Create an array from [1...N]
Y"  % Perform run-length decoding to elacticize the string
    % Implicitly display the result
share|improve this answer

Retina, 62 bytes

It wasn't as easy or short as I thought it'd be. Note that the code contains no spaces. They are all tabs (which are rendered incorrectly here), and the last line is blank.

.*
$0¶ ¶
{+`^(.)(.*)¶    (.*¶.*)
$1$2    ¶$3$1
(   +)¶
¶   $1
}`^.

    |¶

Try it online

share|improve this answer

NARS2000, 6 bytes

⍳∘⍴/⊙⊢

⍳∘⍴ enumeration of the argument... (indices of its length)
/⊙ replicates the elements of...
the unmodified argument

share|improve this answer

K/Kona, 14 bytes

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

Usage:

k){,/(1+!#x)#'x}"A and B"
"A  aaannnnddddd      BBBBBBB"
share|improve this answer

Julia, 34 bytes

!s=s>""?!s[1:(e=end)-1]*s[e:e]^e:s

Try it online!

share|improve this answer
    
Your solution was good. But I managed to beat it. – Glen O 12 hours ago
    
I saw. I had c%n="$c"^n;~s=join([s[r=1:end]...].%r), but that's actually longer. split was the missing piece of the puzzle. – Dennis 6 hours ago

Python 2.7 - 47 Bytes

''.join([s[i-1]*i for i in range(1, len(s)+1)])

where 's' is the given string Output:

welcome: weelllccccooooommmmmmeeeeeee
00004:   000000000044444
Why:     Whhyyy
SKype:   SKKyyyppppeeeee
A and B: A  aaannnnddddd      BBBBBBB
share|improve this answer

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

share|improve this answer
    
Welcome to the site! =) – Dr Green Eggs and Iron Man 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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