title: Is this number a repdigit?

text:
# Question
Title: Is this number a repdigit?
## Challenge

A repdigit is a non-negative integer whose digits are all equal.

Create a function or complete program that takes a single integer as input and outputs a truthy value if the input number is a repdigit in base 10 and falsy value otherwise.

The input is guaranteed to be a *positive* integer.

You may take and use input as a string representation in base 10 with impunity.

## Test cases

These are all repdigits below 1000.

```
1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
111
222
333
444
555
666
777
888
999

```

A larger list can be found on OEIS.

## Winning

The shortest code in bytes wins. That is not to say that clever answers in verbose languages will not be welcome.

# Answer
# Brachylog, 1 byte

```
=

```

Try it online!

This acts on integers.

From `src/predicates.pl#L1151`:

```
brachylog_equal('integer':0, 'integer':0, 'integer':0).
brachylog_equal('integer':0, 'integer':I, 'integer':I) :-
    H #\= 0,
    integer_value('integer':_:[H|T], I),
    brachylog_equal('integer':0, [H|T], [H|T]).

```
> 23 votes

# Answer
# C (gcc), ~~33~~ ~~30~~ 29 bytes

```
f(n){n=n%100%11?9/n:f(n/10);}

```

Try it online!
> 21 votes

# Answer
# COBOL, 139 BYTES

I feel like COBOL doesn't get any love in code golfing (probably because there is no way it could win) but here goes:

```
IF A = ALL '1' OR ALL '2' OR ALL '3' OR ALL '4' OR ALL '5' OR
ALL '6' OR ALL '7' OR ALL '8' OR ALL '9' DISPLAY "TRUE" ELSE
DISPLAY "FALSE".

```

A is defined as a PIC 9(4).
> 10 votes

# Answer
# 05AB1E, 1 byte

```
Ë

```

Checks if all digits are equal

Try it online!
> 9 votes

# Answer
# Python 3, 25, 24 19 bytes.

```
len({*input()})>1>t

```

A stdin =\> error code variant.

Returns error code 0 if it's a repdigit - or an error on failure.

Thanks to Dennis for helping me in the comments.
> 7 votes

# Answer
# Haskell, 15 bytes

```
all=<<(==).head

```

Try it online! Takes string input.

Equivalent to `\s->all(==head s)s`. Narrowly beats out alternatives:

```
f s=all(==s!!0)s
f s=s==(s!!0<$s)
f(h:t)=all(==h)t
f(h:t)=(h<$t)==t
f s=(s<*s)==(s*>s)
f(h:t)=h:t==t++[h]

```
> 6 votes

# Answer
## Mathematica, 27 bytes

```
AtomQ@Log10[9#/#~Mod~10+1]&

```

It doesn't beat `Equal@@IntegerDigits@#&`, but it beats the other arithmetic-based Mathematica solution.

Repdigits are of the form **n = d (10m-1) / 9** where **m** is the number of digits and **d** is the repeated digit. We can recover **d** from **n** by taking it modulo 10 (because if it's a rep digit, it's last digit will be **d**). So we can just rearrange this as **m = log10(9 n / (n % 10) + 1)** and check whether **m** is an integer.
> 6 votes

# Answer
# Slashalash, 110 bytes

```
/11/1//22/2//33/3//44/4//55/5//66/6//77/7//88/8//99/9//1/.//2/.//3/.//4/.//5/.//6/.//7/.//8/.//9/.//T..///.//T

```

Try it online!

The /// language doesn't have any concept of truthy and falsey, so this outputs "T" if the input is a repdigit, and does not output any characters if the input is not a repdigit.
> 6 votes

# Answer
# Jelly, ~~2~~ 1 byte

```
E

```

Try it online!
> 5 votes

# Answer
## C (gcc), 41 bytes

```
f(char*s){s=!s[strspn(s,s+strlen(s)-1)];}

```

This is a function that takes input as a string and returns `1` if it is a repdigit and `0` otherwise.

It does this by making use of the `strspn` function, which takes two strings and returns the length of the longest prefix of the first string consisting of only characters from the second string. Here, the first string is the input, and the second string is the last digit of the input, obtained by passing a pointer to the last character of the input string.

Iff the input is a repdigit, then the result of the call to `strspn` will be `strlen(s)`. Then, indexing into `s` will return a null byte if this is the case (`str[strlen(str)]` is always `\0`) or the first digit that doesn't match the last digit otherwise. Negating this with `!` results in whether `s` represents a repdigit.

Try it online!

Thanks to @Dennis for indirectly reminding me of the assign-instead-of-return trick via his insanely impressive answer, saving 4 bytes!
> 5 votes

# Answer
## PHP, ~~25~~ ~~28~~ 25

```
<?=!chop($argn,$argn[0]);

```

remove all chars from the right that are equal to the first and print `1` if all chars were removed.
> 5 votes

# Answer
## R, 31 bytes

```
function(x)grepl("^(.)\\1*$",x)

```

This functions works with string inputs and uses a regular expression to determine whether the input is a repdigit.

### Example

```
> f <- function(x)grepl("^(.)\\1*$",x)
> x <- c("1", "2", "11", "12", "100", "121", "333")
> f(x)
[1]  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE

```
> 5 votes

# Answer
## Regex (ECMAScript), 31 bytes

```
^(x{0,9})((x+)\3{8}(?=\3$)\1)*$

```

Try it online!

Takes input in unary, as usual for math regexes (note that the problem is trivial with decimal input: just `^(.)\1*$`).

Explanation:

```
^(x{0,9})           # \1 = candidate digit, N -= \1
(                   # Loop the following:
  (x+)\3{8}(?=\3$)  # N /= 10 (fails and backtracks if N isn’t a multiple of 10)
  \1                # N -= \1
)* $                # End loop, assert N = 0

```
> 5 votes

# Answer
# Octave, 11 bytes

```
@(s)s==s(1)

```

Try it online!

Takes the input as a string.

It checks all characters for equality with the first characters. If all are equal, the result will be a vector with only `1` (true in Octave), otherwise there will be at least one `0` (false in Octave). Here's a proof.
> 4 votes

# Answer
# C#, 42 33  28 bytes

```
i=>i.Replace(i[0]+"","")==""

```

`i` has to be a string.

Shaved down a lot thanks to @LethalCoder
> 4 votes

# Answer
# APL, 5 bytes

*2 bytes saved thanks to @KritixiLithos*

```
⍕≡1⌽⍕

```

Try it online!
> 4 votes

# Answer
# grep, 17 bytes

```
grep -xP '(.)\1*'

```

Matches any string that's a repetition of its first character.
> 4 votes

# Answer
## JavaScript (ES6), ~~23~~ 21 bytes

*Saved 2 bytes thanks to Neil*

Takes input as either an integer or a string. Returns a boolean.

```
n=>/^(.)\1*$/.test(n)

```

### Demo

```
let f =

n=>/^(.)\1*$/.test(n)

console.log(f(444))
console.log(f(12))
```
> 3 votes

# Answer
# Japt, 4 bytes

```
¥çUg

```

Try it online!
> 3 votes

# Answer
# Braingolf, 6 bytes

```
iul1-n

```

Try it online!

Unfortunately, Braingolf's implicit input from commandline args can't accept an all-digits input as a string, it will always cast it to a number, so instead the solution is to pass it via STDIN, which adds 1 byte for reading STDIN (`i`)

## Explanation:

```
iul1-n
i       Read from STDIN as string, push each codepoint to stack
 u      Remove duplicates from stack
  l     Push length of stack
   1-   Subtract 1
     n  Boolean negate, replace each item on stack with 1 if it is a python falsey value
        replace each item on stack with 0 if it is a python truthy value
        Implicit output of last item on stack

```

After `u`, the length of the stack equals the number of unique characters in the input, subtracting 1 means it will be `0` if and only if there is exactly 1 unique character in the input, `0` is the only falsey number in Python, so `n` will replace `0` with `1`, and everything else with `0`.
> 3 votes

# Answer
# Ohm, 4 bytes

```
Ul2<

```

Try it online!

### Explanation

```
 Ul2<
 U    # Push uniquified input
  l   # Length
   2< # Is it smaller than 2?

```
> 3 votes

# Answer
# Java, ~~38~~ ~~33~~ 23 bytes

```
n->n.matches("(.)\\1*")

```

`n` is a `String`, naturally.

Note that there is no need for `^...$` in the regex since it's automatically used for exact matching (such as the `match` method), compared to finding in the string.

Try it!

## Saves

* -5 bytes: used `String` since "You may take and use input as a string with impunity."
* -10 bytes: regex is apparently a good fit.
> 3 votes

# Answer
# Java, 21 bytes:

```
l->l.toSet().size()<2

```

`l` is a `MutableList<Character>` from eclipse collections.
> 3 votes

# Answer
# Kotlin, ~~28~~ 19 bytes

```
{it.toSet().size<2}

```

Try it online!

Takes input as a `String` because

> You may take and use input as a string representation in base 10 with impunity.

## Explanation

```
{
    it.toSet()     // create a Set (collection with only unique entries)
                   // out of the characters of this string
        .size < 2  // not a repdigit if the set only has one entry
}

```

If you don't like the fact it takes a `String`, you can have one that takes an `Int` for **24 bytes**.

```
{(""+it).toSet().size<2}

```
> 3 votes

# Answer
# Neim, 1 byte

```

```

Simply checks that all elements are equal.

Without builtin, 2 bytes:

```

```

Explanation:

```
     Calculate unique digits
     Get the length

```

This works because only `1` is considered truthy in Neim, and everything else is falsy.

Alternatively, for 4 bytes:

```
μ

```

Explanation:

```
      Calculate unique digits
       Join list into an integer
      Check that is is less than
  μ    Ten.

```

Try it!
> 2 votes

# Answer
# PHP, 30 bytes

```
<?=($a=$argn).$a[0]==$a[0].$a;

```
> 2 votes

# Answer
# QBasic 4.5, 55 bytes

```
INPUT a
FOR x=1TO LEN(STR$(a))
c=c*10+1
NEXT
?a MOD c=0

```

I've mathed it! The FOR-loop checks the number of digits in the input, then creates `c`, which is a series of 1's of length equal to the input. A number then is repdigit if it modulo the one-string == 0.

Try it online! Note that the online interpreter is a bit quirky and I had to write out a couple of statements that the DOS-based QBasic IDE would expand automatically.
> 2 votes

# Answer
# C, 38 bytes

```
f(char*s){return*s^s[1]?!s[1]:f(s+1);}

```

Recursively walks a string. If the first two characters differ (`*s^s[1]`) then we succeed only if we're at the end of the string (`!s[1]`) otherwise we repeat the test at the next position (`f(s+1)`).

## Test program

```
#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv)
        printf("%s: %s\n", *argv, f(*argv)?"yes":"no");
}

```
> 2 votes

# Answer
# R, 25 bytes

```
grepl("^(.)\\1*$",scan())

```

Try it online

Best non-regex solution I could come up with was 36 bytes:

```
is.na(unique(el(strsplit(x,"")))[2])

```
> 2 votes

# Answer
# Cubix, 15 bytes

```
uOn@ii?-?;.$@<_

```

Try it online!

```
    u O
    n @
i i ? - ? ; . $
@ < _ . . . . .
    . .
    . .

```

Watch It Run

Outputs 1 for truthy and nothing for falsey

Very simply read reads in the input one character at a time. It takes the current character away from the previous. If a non zero result then it halts immediately. Otherwise it continues inputting and comparing until the EOI. On EOI (-1), negate and exit
> 2 votes

# Answer
# MATL (6 5 bytes or 2 bytes for Luis Mendo solution)

```
Vun1=

```

Try it online!

## Explanation

```
V     % convert to string
un    % find unique characters and count them
1=    % if there is only one unique character, then we pass.

```

Luis Mendo solution (see comments):

```
&=

```

Outputs a truthy array (all 1's) if repdigit, or a falsy array (some 0 in the array) if not a perfect repdigit.

Try it online!
> 2 votes

# Answer
# Excel, 24 bytes (assuming Tab is 1 byte)

```
=LEFT(B1,1);=A1&B1=B1&A1

```

# Excel, ~~28~~ 27 bytes

```
=A1=MID(A1,2,A1)&LEFT(A1,1)

```
> 2 votes

# Answer
# , 6 bytes

```
1=#@~.

```

Try it online!

Take unique elements; does its length equal 1?

```
/:-:\:

```

Try it online!

Does ascending sorting order equal descending sorting order?

```
-:##{.

```

Try it online!

Does the first element, duplicated to the length, equal the original?

```
-:1&|.

```

Try it online!

Does the input, rotated once, equal itself?
> 2 votes

# Answer
## brainfuck, 21 bytes

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

```

With a little formatting:

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

```

Try it online

Prints the repeated digit for true, and NUL for false.

Compares adjacent digits in a loop, and in the case of inequality, shifts pointer so that all subsequent comparisons will also result in inequality, and the cell to the right will be zero upon exiting the loop.

### Variant for stricter output rules, 25 bytes

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

```

Formatted:

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

```

Try it online

This version prints `\x01` for true.
> 2 votes

# Answer
# Python, ~~27~~ 22 bytes:

Just to get things started.

```
lambda x:len(set(x))<2

```

Converts to a string, converts the string into a set of all distinct characters in that string, and checks whether there aren't multiple elements in the set.

5 bytes saved thanks to @LeakyNun's reminder.
> 1 votes

# Answer
# Python 3, 23 bytes

```
lambda s:s==s[0]*len(s)

```

Try it online!

Not shorter than @shadow's answer, but I thought it was interesting. Should work in Python 2 as well.
> 1 votes

# Answer
# QBIC, ~~36~~ 23 bytes

```
[_l!:$||p=p*z+1]?b%p=0

```

## Explanation

```
    :     Read a number from the cmd line
   ! $    cast it to string
 _l   |   Take its length
[      |  And run a FOR-loop from 1 to that length
p=        p starts out as 0. set it to
  p*z       itself multiplied by 10 (z=10 in QBIC) (still 0 on the first run
  +1        then add 1. On consecutive FOR-loops yields 1, 11, 111, ....
]         Close the FOR loop
?b%p=0    PRINT -1 if b mod p is 0 (ie 444 % 111 = 0), or 0 otherwise

```
> 1 votes

# Answer
# Ruby, 13 bytes (12 + '-n' flag)

```
p~/^(.)\1*$/

```

Try it online!
> 1 votes

# Answer
## Clojure, ~~17~~ 12 bytes

> You may take and use input as a string representation in base 10 with impunity.

Oh in that case:

```
#(apply = %)

```

Original:

```
#(apply =(str %))

```
> 1 votes

# Answer
# C#, 38 bytes

```
using System.Linq;s=>s.All(c=>c==s[0])

```

Or alternatively for 44 bytes:

```
using System.Linq;s=>s.Distinct().Count()==1

```
> 1 votes

# Answer
## \>\<\>, ~~26~~ 24 bytes

```
!vi:0(?v::&r&=?
 >0n;n1<

```

Reads the input as a string and reads every character in a loop

```
  i               // Take the next character and pushes it onto the stack
   :0(?v          // If the end of the input has been reached, goto the successful termination code
        ::        // Duplicate the top of the stack twice
!v         &r&=?  // Pop the top of the stack, pop the bottom of the stack, and compare them. If they are not equal, goto the failure termination code
 >0n;            // Failure termination code. Prints a 0 and terminates
    ;n1<         // Success termination code. Prints a 1 and terminates

```
> 1 votes

# Answer
# Perl 6, 12 bytes

```
{[==] .comb}

```

Reduces the list of characters in the input number with the numeric equality operator.
> 1 votes

# Answer
# AWK, 33 bytes

```
BEGIN{FS=""}{$0=NF==gsub($1,"")}1

```

Try it online!

Replaces all characters in the input with the first character and compares the changed count to the total number of characters.
> 1 votes

# Answer
## PowerShell, 23 bytes

```
"$args"-match'^(.)\1*$'

```

Save as repdigit.ps1 and run with `PS C:\wherever\repdigit.ps1 444`, outputs True or False.

If you want the Python len(set(input))==1 style, it costs more at 32 bytes:

```
@($args-split''|group).count-eq2

```

(Noting that the split on the space between chars also outputs an empty start and end string as well as the characters).
> 1 votes

# Answer
# PHP, 28 bytes

```
<?=!count_chars($argn,3)[1];

```

`count_chars` with `mode=3` creates a string with all different characters in `$argn`.
If there is only one, the second character will be empty == falsy.

Run as pipe with `-F`.
> 1 votes

# Answer
# Smalltalk, ~~21~~ 19 bytes

```
[:s|s asSet size<2]

```

Try it online!

You can execute the block above by sending the message `value:` to the block with a `String`. A `String` in Smalltalk is written with single quotes. A longer version of the block could accept an `Integer`. It would take ~~30~~ 28 bytes.

```
[:i|i asString asSet size<2]

```

I tried both solutions in the current online version of Amber Smalltalk and Pharo Smalltalk version 6.0.

Thanks to the suggestion in the comments I was able to remove the spaces before and after the `<`. It's been many years since I wrote Smalltalk but I doubt I ever tried that in practice. The shorter version worked in both versions of Smalltalk I tested.
> 1 votes

# Answer
## Check, ~~135~~ ~~134~~ ~~132~~ 124 bytes

```
 [r            #v
#:>10%:]R+r->\#v#?
#v
# >10-\)\#     # ?
d #             ^
 #R:
:>=r,#v
#ddd[=#(:@:@=R-?
d\:!:R *
o>]=d#^

```

Input should be passed as a command-line argument. Outputs some unprintables for truthy and only zero bytes for falsey. Always terminates with an `IndexError` due to the fact that it abuses an interpreter bug.

### How does it work?

This code is divided into two segments. The first half turns the input integer into a list of digits, and the second half checks that all of its digits are equal to the first digit (i.e. they are all equal).

It roughly corresponds to the following pseudocode:

1. Read input and call it *i*.
2. Create an empty array and store it in the register. (`[r`)
3. If *i* is 0, go to step 13.
4. Take the number modulo 10. Call it *x*.
5. Prepend *x* to the register and store it back in the register.
6. Subtract *x* from *i*.
7. Create a counter, starting at 0.
8. If *i* is 0, go to step 12.
9. Increment the counter.
10. Decrement *i* by 10.
11. Go back to step 8.
12. Set *i* to whatever value is now in the counter.
13. Go back to step 3.
14. Load the register, which is now an array containing the digits of the input. Call this *d*.
15. Get the first element in *d* and store it in the register.
16. Create a counter called *j*, initialized to the length of *d*.
17. Decrement *j*.
18. If the *j*th element of *d* is not equal to the value of the register, crash the program. (We found a digit that is not correct.)
19. Otherwise, print some random junk *!j* times. This only prints something if *j == 0*.
20. Create an array of length 1 and get the *!j*th element. This will crash the program if *j == 0*.
21. If the program has not yet crashed, *j* must not yet be zero, so go back to step 17.
> 1 votes

# Answer
# Julia, 30 bytes

```
f(n)=length(Set(string(n)))==1

```
> 1 votes

# Answer
## F#, 38 bytes

```
let f n=Seq.length(Seq.countBy id n)=1

```

Try it online!
> 1 votes

# Answer
# QBasic, ~~37~~ 32 bytes

```
INPUT n$
?n$=STRING$(LEN(n$),n$)

```

*-5 bytes thanks to steenbergh*

The `STRING$` function takes two arguments, a number `n` and a string `s$`, and constructs a string consisting of `n` copies of the first character of `s$`.\* So this code reads our number as a string `n$`, generates a string consisting of `LEN(n$)` copies of `n$`'s first character, and checks to see if it is equal to `n$`.

* The second argument can also be an integer codepoint, in which case it repeats the character corresponding to that codepoint.
> 1 votes

# Answer
# Pepe, ~~69~~ 60 bytes

```
REeErEEEEEREEEeeEREEEEeEeEREEEEEEeREEEeREEEEEerrEEreEErEereE

```

Try it online!

**How it works?**

It takes the greatest digit and subtracts it from the least digit. Repdigit numbers always evaluate to 0.

```
REeE             # Takes a number (stack r)
rEEEEEREEEeeE    # Splits by digits
REEEEeEeE        # Sorts them
REEEEEEe         # Copies first digit to other stack
REEEe            # Move pointer to last in stack r
REEEEEe          # Subtract stack R to stack r
rrEErEEEEErEereE # Print if 0, else none

```
> 1 votes

# Answer
# Whitespace, ~~96~~ 93 bytes

```
[S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S S S T   T   S S T   S S N
_Push_100][T    S T T   _Modulo][S S S T    S T T   N
_Push_11][T S T T   _Modulo][N
T   S S N
_If_0_Jump_to_label_NEXT][S S S T   S S T   N
_Push_9][S N
T   _Swap_top_two][T    S T S _Integer_division][T  N
S T _Print_as_integer][N
S S S N
_Create_Label_NEXT][S S S T S T S N
_Push_10][T S T S _Integer_division][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Port of *@Dennis♦*' C answer, so also outputs a positive digit (`[1,9]`) as truthy and `0` as falsey.

Try it online (with raw spaces, tabs and new-lines only).

**Pseudo-code:**

```
Integer i = STDIN as integer
Start LOOP:
  If(i modulo-100 modulo-11 == 0):
    i = i integer-divided by 10
    Go to next iteration of LOOP
  i = 9 / i
  Print i to STDOUT as integer
  Stop the program with an error

```
> 1 votes

# Answer
# Pascal (FPC), ~~81~~ ~~75~~ 68 bytes

```
var n:string;begin read(n);write(n=StringOfChar(n[1],length(n)))end.

```

Try it online!

It seems that taking a number as string is shorter.

---

### 75 bytes - taking the number as integer:

Thanks to @Ørjan Johansen for -6 bytes - `mod 100 mod 11` trick

```
var n:word;begin read(n);while n mod$64mod$B=0do n:=n div$A;write(n<=9)end.

```

Try it online!

`$64`, `$B` and `$A` are hexadecimal constants, they eliminate some whitespace that would be needed for their decimal counterparts.
> 1 votes

# Answer
# Taxi, ~~730~~ 706 bytes

*-24 bytes by eliminating linebreaks.*

Clever answer in a verbose language? Check and check.

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Pickup a passenger going to Cyclone.[B]Switch to plan D if no one is waiting.Pickup a passenger going to Crime Lab.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Crime Lab.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 2 r 2 r.Switch to plan C if no one is waiting.Pickup a passenger going to Cyclone.Go to Fueler Up:n.Go to Chop Suey:n 3 r 1 l.Switch to plan B.[C]0 is waiting at Writer's Depot.Go to Writer's Depot:n 4 l 2 l.Pickup a passenger going to Cyclone.Go to Chop Suey:n 3 r 3 r.[D]Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Post Office.Go to Post Office:s 1 l 2 r 1 l.

```

Try it online!

Try it online with linebreaks!

Doesn't return to the Taxi Garage after the program ends, so the boss fires me, and it exits with an error.

What this program actually does is checks whether or not the input consists of any repeating character, and outputs that character if it does, or `0` if it doesn't.

# Alternative solution, ~~602~~ ~~582~~ ~~541~~ 445 bytes

*-20 bytes by eliminating linebreaks.*

*-41 bytes by having the program error out upon a false result.*

*-96 bytes by having the program output via error message.*

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Pickup a passenger going to Cyclone.[B]Switch to plan C if no one is waiting.Pickup a passenger going to Crime Lab.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Crime Lab.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 2 r 2 r.Pickup a passenger going to Cyclone.Go to Fueler Up:n.Go to Chop Suey:n 3 r 1 l.Switch to plan B.[C]

```

Try it online!

Try it online with linebreaks!

This alternative solution errors out with `The boss couldn't find your taxi in the garage. You're fired!` if the input is a repdigit, and `no outgoing passengers found` if the input is not a repdigit (meaning this also works with `0`...or `00`, or `000`...).
> 1 votes

# Answer
# Pepe, 48 bytes

```
rrEEreeeEEeeeErEeREEeREEREEEEEEErEEEEreErEEEeReE

```

Outputs `1` if number is a repdigit, nothing otherwise.

Try it online!

## Explanation

(for input `45`. `52` and `53` are charcodes of digits)

```
rrEE          # Create label 0, implicitly push 0 to the second stack [] [0]
  reeeEEeeeE    # Print "1"
rEe           # Return

REEe          # Start: Take input as charcodes to the first stack [52,52,53] [0]
REE           # Create label I (1)
  REEEEEEE      # Move first item in first stack to the other [52,53] [0, 52]
  rEEEE         # Reset second stack pointer position [>52, 53] [>0, 52]
  reE           # If item in first stack equals the first item in the second stack (0),
                #   call label 0. It will only be true if first stack is empty
                #   because it will implicitly give 0.
rEEEe           # Move second stack pointer to the end [>52, 52] [0, >52]
ReE           # Repeat if items are the same (52 == 52), end program otherwise
reeeEEeeee    # Optional: Print 0.

```
> 1 votes

# Answer
# naz, 50 bytes

```
2a2x1v1r2x2v1x1f1r3x1v2e3x2v1e0m1o0x1x2f0m1a1o0x1f

```

Works for any input integer, provided it's passed as a file terminated with the control character STX (U+0002).

**Explanation** (with `0x` commands removed)

```
2a2x1v                 # Set variable 1 equal to 2
1r2x2v                 # Read the first byte of input and store it in variable 2
1x1f                   # Function 1
    1r                 # Read a byte of input
      3x1v2e           # Jump to function 2 if it equals variable 1
            3x2v1e     # Jump back to the start of the function if it equals variable 2
                  0m1o # Otherwise, output 0
1x2f                   # Function 2
    0m1a1o             # Output 1
1f                     # Call function 1

```
> 1 votes

# Answer
# Pip, 3 bytes

```
$=a

```

fold by equality.

Try it online!
> 1 votes

# Answer
# Swift (24 / 17 bytes)

**Console App (24 bytes):**

```
Set(readLine()!).count<2

```

**Function (17 bytes):**

```
{Set($0).count<2}

```

Usage example:

```
let isRepdigit: (String) -> Void = {Set($0).count<2}
print(isRepdigit("234")) // prits false
print(isRepdigit("66666")) // prints true

```
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Simply checks if all the digits are equal to each other
> 1 votes

# Answer
# Scratch 3.0, 20 blocks/148 bytes

```
define(z)
set[o v]to(1
set[i v]to(1
repeat(length of(z)
if <not<(letter(i)of(z))=(letter(1)of(z))>>then
set[o v]to(0
end
set[i v]to((i)+(1
end
say(o

```

Try it on Scratch

I did the most logical thing and answer this with scratch. Essentially, we loop through every character and see if it equals the first character. If any character doesn't equal the first, the output is set to falsey
> 1 votes

# Answer
# Thunno 2, 1 byte

Attempt This Online!

Built-in that works on numbers.
> 1 votes

# Answer
# JavaScript (Node.js), 26 ~~27~~ bytes

*(Solutions without regex. They all take input as a string. Luckily for some of them, OP guaranteed that the input can't be zero)*

> -1 byte thanks to @Shaggy

Checking that there is no character different from the first :

```
s=>![...s].some(c=>c-s[0])

```

Try it online!

---

Checking that every character is the same as the first (**27 bytes**) :

```
s=>[...s].every(c=>c==s[0])

```

---

Checking that the parameter is equal to the first character repeated `parameter.length` times (**27 bytes**) :

```
s=>s==s[0].repeat(s.length)

```

---

Checking that the parameter divided by its first character is equal to `1` repeated `parameter.length` times (**31 bytes**) :

```
s=>s/s[0]=="1".repeat(s.length)

```

---

**More mathematical ways** (could probably be a lot shorter in other languages ?) :
There is a special rule that only repdigits follow.
For example, `4444 +1` in `base 4+1` gives `10000` in the same base, and we can recognize this particular pattern (still without using regex).
Using the same example, checking that `10000` (made from concatenation and repetition) from `base 4+1` to `base 10`, minus `4444` (the parameter) with same base conversion, gives exactly `1`. The `4` for the base conversion comes from the first character of the parameter (**63 bytes**) :

```
s=>parseInt(1+"0".repeat(s.length),a=s[0]*1+1)-parseInt(s,a)==1

```

---

Using the same example, checking that `4444` (the parameter) from `base 4+1` to `base 10`, plus `1`, converted back to its original base, gives a number that when inverted from right to left (to get rid of the previously trailing zeroes), is exactly `1`. The `4` for the base conversion comes from the highest digit of the parameter (**76 bytes**) :

```
s=>[...(parseInt(s,a=Math.max(...s)+1)+1).toString(a)].reverse().join``*1==1

```
> 1 votes

# Answer
# Rockstar, 76 bytes

```
listen to N
cut N
roll N in D
O's 1
while N and O
let O be D's roll N

say O

```

Try it (Code will need to be pasted in)
> 1 votes

# Answer
# Arturo, 15 bytes

```
$->x[{}=x--x\0]

```

Try it!

```
$->x[       ; a function taking an input x
    {}=     ; is the empty string equal to...
    x--x\0  ; x without its first element
]           ; end function

```
> 1 votes

# Answer
# Cheddar, 16 bytes

```
s->s.len*s[0]==s

```

Try it online!

## Integer input, 29 bytes

```
n->(s->s.len*s[0]==s)("%d"%n)

```

Try it online!
> 0 votes

# Answer
# Tcl, 53 bytes

```
proc r n {expr 1==1[string trim $n [string in $n 0]]}

```

"string trim" removes leading and trailing occurrences of all its second argument's characters from its first argument (usually used for whitespace). Second argument here is the first digit of $n. For a repdigit an empty string remains, and attaching that to 1 remains 1. For number 42424, 242 would remain after the trim, so 1 is not equal to 1242.

PS: attaching to 1 is a golfing-thing that saved two bytes versus comparing the trim with empty string.
> 0 votes

# Answer
## Pyke, 3 bytes

```
}t!

```

Try it here!

```
}   -   uniquify(input)
 t  -  ^[:-1]
  ! - not ^

```
> 0 votes

# Answer
# Noether, 39 bytes

```
""~bI~aL(ai/~c{bc/}{}{bc+~b}i1+~i)bL1=P

```

**Try it here!**

It takes input as a number enclosed in quotation marks.

This works by looping through the input string, and, at the start, adding the first character to the string, B. As it loops, if the current character in the input isn't in B, it is appended to B. At the end, if the number is a repdigit, B will only be one character long.

Outputs 1 for true, 0 for false.
> 0 votes

# Answer
# PHP, 34 bytes

```
<?=preg_match('#^(.)\1*$#',$argn);

```

Try it online!
> 0 votes

# Answer
# Excel, 31 bytes

```
=MOD(A2,10)*(10^LEN(A2)-1)/9=A2

```
> 0 votes

# Answer
# , 13 bytes

```
ylÍ"/.
ñ/ä
d

```

Try it online!

Leaves a string of `.`s if truthy, nothing if falsy (empty strings are truthy in Vim/V and vice versa)
> 0 votes

# Answer
# , 6 bytes

```
ø^ˆ±*$

```

Try it online!

Hexdump:

```
00000000: f85e 88b1 2a24                           .^..*$

```

This uses a brand new operator that I haven't used in any PPCG answers before. The `ø` operator will count the number of matches of a given regex. In this case, the (compressed) regex is:

```
/^\(.\)\1*$/

```

That is, any character at the start of the line, followed by only that character until the end of the line.
> 0 votes

# Answer
**Swift , 53 Bytes**

```
var s=readLine()!,r=Set(s.characters);r.count>1 ?0:1

```
> 0 votes

# Answer
# TI-BASIC, ~~17~~ 16 bytes

```
log(1+.9X/fPart(.1X:Ans=int(Ans

```

Takes input on `X`. **TI-BASIC** is token based, all tokens are one byte.
> 0 votes

# Answer
## CJam, 6 bytes

```
qL|,1=

```

### Explanation:

```
q  e# Get the input: "1311211"
L| e# Get unique elements: "132"
,  e# Length: 3
1= e# Equal to 1: 0 (false)

```
> 0 votes

# Answer
# Batch, 177 bytes

```
@echo off
set s=
set z=
<nul set/p=.%1>t
for /f "usebackq" %%G in ('t')do set z=%%~zG
for /l %%G in (2,1,%z%)do call set s=1%%s%%
set/ar=%1%%%s%
if %r%==0 echo %r%&exit/b
echo 1

```

Not properly golfed, yet.
> 0 votes

# Answer
# Pushy, 5 bytes

```
sK=P#

```

**Try it online!**

```
                                              Falsy Example:      Truthy Example:
       \ Implicit: Input on stack             [22121]             [5555]
s      \ Split into digits                    [2, 2, 1, 2, 2]     [5, 5, 5, 5]
 K=    \ Pop last, compare with all others    [1, 1, 0, 1]        [1, 1, 1]
   P#  \ Print the stack's product            PRINT: 0            PRINT: 1

```

# 6 bytes

I prefer this method as it's sweet and simple, but unfortunately it's one byte longer:

```
suLtn#

```

**Try it online!**

```
        \ Implicit: Input on stack
s       \ Split into digits
 u      \ Make stack into a set of itself
  Lt    \ Get the stack length - 1
        \ This will be 0 for a valid repdigit, a positive value otherwise
    n   \ Boolean negate: this maps 0 -> 1, and everything else to 0.
     #  \ Print result.

```
> 0 votes

# Answer
# Tcl, 48 bytes

```
proc R n {expr 1[regsub -all ^(.)\\1* $n ""]==1}

```

Try it online!

---

~~Tcl, 52 bytes
```
proc R n {expr [llength [lsort -u [split $n ""]]]<2}

```
Try it online!
~~
> 0 votes

# Answer
# \>\<\>, 12 bytes

```
1l2=?n@:}=*!

```

Try it online!

Takes input through the `-s` flag and checks whether every digit is the same.
> 0 votes

# Answer
# Pari/GP, 21 bytes

```
n->#Set(digits(n))==1

```

Try it online!
> 0 votes

# Answer
# SmileBASIC 3, 26 bytes

```
INPUT N$?N$[0]*LEN(N$)==N$

```

Takes input as a string, prints 0 for false and 1 for true. If we repeat the first character of the input `length(input)` times and that is equal to the input, then it's a repdigit.
> 0 votes

# Answer
## PHP, 42 Bytes

**Try it online**

(42 Bytes because i forgot Towel day on may 25)

**Code**

```
<?=!(($a=$argv)%str_repeat(1,strlen($a)));

```

**Explanation**

Every number like `11, 22222,5555555555` always will be dvisible by `1 times the number length` it just checks that, if the `%` between the numbers is `0` outputs `1` else empty.
> 0 votes

# Answer
# Forth (gforth), 87 bytes

```
: m 10 /mod swap ; : f 1 swap m >r begin ?dup 0> while m r@ = rot * swap repeat rdrop ;

```

Try it online!

### Explanation

The algorithm is approximately:

1. Divide by 10, take remainder and store on return stack
2. Repeatedly divide by 10 and compare remainder to stored value
3. When quotient equals 0, stop loop and clean return stack

### Code Explanation

```
: m 10 /mod swap ;        \ helper to grab the quotient and remainder after dividing by 10

```

---

```
1 swap                    \ place 1 as a result value on the stack and move to the bottom
m >r                      \ divide by 10 and place remainder on the return stack
begin                     \ start an indefinite loop
  ?dup 0>                 \ duplicate if not equal to 0 and check if greater than 0
while                     \ if greater than 0 execute loop body, else go the end of the loop
  m r@ =                  \ divide by 10, check if remainder equals our check value
  rot *                   \ move the result value to the top and multiply by result
  swap                    \ move the result value back to the boottom
repeat                    \ end the loop body
rdrop                     \ clean the return stack

```
> 0 votes

# Answer
# Pyth, ~~4~~ 3 bytes

```
!t{

```

Try it online!
*-1 thanks to Erik the Outgolfer!*

Takes input as a string.
> 0 votes

# Answer
# APL(NARS), 16 chars, 32 bytes

```
{(⍴w)=+/w=↑w←⍕⍵}

```

test:

```
  {(⍴w)=+/w=↑w←⍕⍵}¨1 2 23 33 93 9999999
 1  1  0  1  0  1

```
> 0 votes

# Answer
# MathGolf, 3 bytes

```
▀£┴

```

Try it online!

Takes input as a string.

### Explanation:

```
▀    Get unique characters
 £   Get length of list
  ┴  Is equal to one?

```
> 0 votes

# Answer
# Pyt, 2 bytes

```
ą≡

```

Try it online!

**Explanation:**

```
   Implicit input
ą  Split digits
 ≡ Are all elements equal?

```
> 0 votes

# Answer
# Stax, 4 bytes

```
ë@╛α

```

Run and debug it

## Unpacked

```
Eu%v!

```
> 0 votes

# Answer
# Prolog, 43 bytes

```
f(N,D):-N==0;O is N//10,D is N-O*10,f(O,D).

```

Run the query with `f(666,D)` (or whatever other number you have). If it's a repdigit, it will return a value for `D`, otherwise, it will return false.

Try it in SWISH (By the way, I think if you make changes directly without creating a new notebook, it may modify the original, so please don't mess with it :))
> 0 votes

# Answer
# Zsh `--extendedglob`, 14 bytes

```
>$1
: ^{1..9}#

```

Try it online!

Outputs via exit code: `0` is not a repdigit, `1` is a repdigit.

* `>$1` \- create the file according to the input
* `^{1..9}#` \- construct the string `^1# ^2# ... ^9#`
* then find a file matching *all* of the patterns `^1#` `^2#` ... `^9#`
    + `#` means zero or more of the preceding digit (but since a file must be at least 1 character, it actually means 1 or more)
    + `^` means logical NOT
        - by DeMorgan's law, this creates a logical OR of the patterns `^1#` `^2#` ... `^9#` (just with inverted output, but we can cope with that)
    + if no file matching all of these patterns exists - that is, the file is *not not* a repeated digit - there will be an error and the exit code will be `1`.
* `:` \- and do nothing with it (otherwise it would try to execute the file as a command, which would also exit with an error)

`--extendedglob` is required to enable the `^` and `#` glob operators.
> 0 votes

# Answer
# Factor, 19 bytes

```
[ present all-eq? ]

```

Try it online!
> 0 votes

---
Tags: code-golf, math, number, arithmetic, decision-problem
---


title: Write a program to elasticize strings

text:
# Question
Title: Write a program to elasticize strings
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 :)

# Answer
# Jelly, 3 bytes

Code:

```
ĖP€

```

Explanation:

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

```

Uses the **Jelly encoding**. Try it online!.
> 36 votes

# Answer
# 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

```
> 17 votes

# Answer
## 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)
> 13 votes

# 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.
> 10 votes

# Answer
# 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.
> 9 votes

# Answer
## 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

```
> 8 votes

# Answer
# Python, 39 bytes

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

```

Test it on Ideone.
> 8 votes

# 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"]

```
> 7 votes

# 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.
> 6 votes

# 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>
```
> 5 votes

# Answer
# APL (dzaima/APL), ~~6~~ 5 bytes

```
⍳∘≢⌿⊢

```

Try it online!

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

# Answer
# APL (8)

```
{⍵/⍨⍳⍴⍵}

```

I.e.:

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

```

Explanation:

* `⍴⍵`: length of given vector
* : numbers 1..N
* `⍵/⍨`: replicate each element in  N times.
> 4 votes

# Answer
# 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"

```
> 4 votes

# Answer
# 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.

```
> 4 votes

# Answer
# , ~~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.
> 4 votes

# Answer
## 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 `-join`ed 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

```
> 3 votes

# Answer
# MATLAB, 23 bytes

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

```

Creates an anonymous function `ans` that can be called using `ans('stringtoelacticize')`
> 3 votes

# Answer
## /Kona, 14 bytes

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

```

Usage:

```
k){,/(1+!#x)#'x}"A and B"
"A  aaannnnddddd      BBBBBBB"

```
> 3 votes

# 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
}

```
> 3 votes

# 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 :-).
> 3 votes

# Answer
## 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.
> 3 votes

# Answer
# 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"`
> 3 votes

# Answer
# PHP, 68 bytes

```
<?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);

```
> 3 votes

# Answer
# 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)

```
> 3 votes

# Answer
# Vyxal `s`, 2 bytes

```
Þż

```

Try it online, or see a 3 byte flagless version
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# \>\<\> (Fish), 33 bytes

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

```

Try the animated version

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

# Answer
# Pyth - 5 bytes

*1 byte saved thanks to @FryAmTheEggman.*

```
s*VSl

```

Test Suite.
> 2 votes

# Answer
## 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

```
> 2 votes

# 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'`
> 2 votes

# Answer
## C#, 81 Bytes

```
void f(string s){for(int i=0;i<s.Length;i++)Console.Write(new String(s[i],i+1));}

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
## Python, 40 bytes

```
f=lambda s,i=1:s and s[0]*i+f(s[1:],i+1)

```
> 2 votes

# Answer
# Julia, 34 bytes

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

```

Try it online!
> 2 votes

# Answer
# TSQL, 97 bytes

Golfed:

```
DECLARE @x varchar(max)='Lobby'
DECLARE @ int=LEN(@x)WHILE @>0SELECT
@x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),@-=1PRINT @x

```

Ungolfed:

```
DECLARE @x varchar(max)='Lobby'

DECLARE @ int=LEN(@x)
WHILE @>0
  SELECT
    @x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),
    @-=1

PRINT @x

```

Try it online
> 2 votes

# Answer
## Mathematica, 46 bytes

```
""<>Table@@@(#^Range@Length@#&@Characters[#])&

```

Unnamed function. Takes the characters of the input string and raises them to the power of their position in the string (i.e. `"abc"` becomes `{"a"^1, "b"^2, "c"^3}`). Yes, MMA don't give a shit 'bout types :-)

The `FullForm` of the above list elements is `Power["a", 1]`, etc.
`Table@@@` acts on the list, replacing the head of each element (in this case `Power`) with `Table`.
Results in `{Table["a"], Table["b", 2], Table["c", 3]}` (because `"a"^1 -> "a"`).
This evaluates to `{"a", {"b", "b"}, {"c", "c", "c"}}` Finally the infix concatenation operator `<>` concatenates this with the empty string.

I exploited the fact that `Power` is `Listable`, i.e. it automatically threads over corresponding elements of lists, but not orderless (because `"a" + 1` would evaluate to `Plus[1, "a"]`).
> 2 votes

# Answer
# LINQPad w/ C#, 82 bytes

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

```

Single output operation.
> 2 votes

# Answer
# C, 84 bytes

```
main(c,v,i,j)char**v;{for(i=0;i<strlen(v[1]);++i)for(j=0;j<=i;++j)putchar(v[1][i]);}

```

This should compile on gcc with no flags. Input is taken through the first command-line argument. E.g.

```
$ ./elasticize Why
Whhyyy
$ ./elasticize SKype
SKKyyyppppeeeee
$ ./elasticize LobbY
LoobbbbbbbYYYYY
$ ./elasticize A and B
A  aaannnnddddd      BBBBBBB

```

Ungolfed:

```
int main(int argc, char** argv) {
    int i, j;
    for(i = 0; i < strlen(argv[1]); ++i) {
        for(j = 0; j <= i; ++j) {
            putchar(v[1][i]);
        }
    }
}

```
> 2 votes

# Answer
# Clojure, 86 bytes

```
(fn[s](apply str(mapcat #(repeat(+(nth % 1)1)(nth % 0))(map list s(range(count s))))))

```

Well, nearly beat C. Create a list of pairs (symbol, its position), then repeat each symbol given number of times and flatten the result list and concatenate the list into one string.

See it here: https://ideone.com/uQNar2
> 2 votes

# Answer
# Jelly, 2 bytes

```
xJ

```

Try it online!
> 2 votes

# Answer
# Zsh, 38 bytes

```
for i (${(s::)@});repeat ++n printf $i

```

Try it online!

-8 bytes thanks to roblogic
> 2 votes

# Answer
# Dart, 47 bytes

```
f(s,[c=0])=>s.split("").map((i)=>i*++c).join();

```

Try it online!
> 2 votes

# Answer
# Knight, ~~33~~ 32 bytes

```
;=i!=sP;W<iLsO+*Gs iT=i+1i"\"O""

```

Try it online!

expanded:

```
; = i ! = s PROMPT
; WHILE < i LENGTH s
    : OUTPUT
        +
            * (GET s i TRUE) (= i + 1 i)
        "\" # so no trailing newline
: OUTPUT "" # now output the trailing newline

```

-1 did `=i!` instead of `;=iF`
> 2 votes

# Answer
# C (clang), 54 bytes

```
i;c;main(j){for(;j=j-1?:read(0,&c,1)*++i;)putchar(c);}

```

Try it online!

### How it works

```
i;            // declares a zero initialized int
main(j){      // j := argc (should be 1, program called with no arguments)
 for(;j=j-1?: // if (j > 1) j = j - 1, otherwise...
 read(0,&c,1) // try to read 1 byte, return number of bytes read (0 on EOF or 1)
 *++i;)       // increment i, j = read? * i (stopping on EOF)
  putchar(c); // write to stdout
}

```

# C (clang), 51 bytes

```
i,j;f(*s){for(i=0;*s;s++)for(j=++i;j--;)printf(s);}

```

This function takes a wide-character string as input and works in the same way as the full program.

Try it online!
> 2 votes

# Answer
# Japt `-m`, 3 bytes

```
+pV

```

Try it here
> 2 votes

# 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
> 1 votes

# 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**
> 1 votes

# Answer
# Ruby, 29 bytes

Try it online

```
->s{i=0;s.gsub(/./){$&*i+=1}}

```
> 1 votes

# Answer
## Pyke, 4 bytes

```
Foh*

```

Try it here!
> 1 votes

# Answer
**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

```
> 1 votes

# Answer
# Oracle SQL 11.2, 125 bytes

```
SELECT LISTAGG(SUBSTR(RPAD(' ',LEVEL+1,SUBSTR(:1,LEVEL,1)),2))WITHIN GROUP(ORDER BY 1)FROM DUAL CONNECT BY LEVEL<=LENGTH(:1);

```
> 1 votes

# Answer
# C, 77 bytes

Not much room for golfing here. If only there were a string repeat operator.

```
i;main(j){char s[999];gets(s);for(;s[i];i++)for(j=0;j<=i;j++)putchar(s[i]);}

```

Try it online! http://ideone.com/UliJfD
> 1 votes

# Answer
# brev, 42 bytes

```
(as-list flatten(over(make-list(+ i 1)x)))

```
> 1 votes

# Answer
# Burlesque, 10 bytes

```
{+..*}wi\[

```

Try it online!

```
{
 +. # Increment
 .* # Repeat
}wi # Apply with 0-index
\[  # Concatenate

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 53 bytes

```
a=>string.Concat(a.Select((c,i)=>new@String(c,i+1)));

```

Try it online!
> 1 votes

# Answer
## Kustom, 67 bytes

This makes use of the fact that an undefined global variable works as empty string. The extra byte is for the name of the defined global variable.

```
$fl(1,tc(len,gv(n)),"i+1","tc(lpad,gv(x),i,tc(cut,gv(n),i-1,1))")$

```

Sort of ungolfed:

```
$fl(
  1,
  tc(len, gv(input)),
  "i + 1",
  "tc(
    lpad,
    gv(undefined),
    i,
    tc(
      cut,
      gv(input),
      i - 1,
      1
    )
  )"
)$

```
> 1 votes

# Answer
# Prolog (SWI), 69 bytes

```
S*O:-append(H,[T],S),maplist([_,Y]>>(Y=T),S,R),H*Y,append(Y,R,O);O=S.

```

Try it online!

I feel like this should be shorter...
> 1 votes

# Answer
# Pip, 14 bytes

```
Fi,#aOa@iXi+1x

```

Try It Online!
> 1 votes

# Answer
# Arturo, 44 bytes

```
$[s][i:0join map split s'c[i:i+1repeat c i]]

```

Try it
> 1 votes

# Answer
# Thunno `J`, \\$9\log\_{256}(96)\approx\\$ 7.41 bytes

```
DLR1+ZZ.P

```

Attempt This Online!

#### Explanation

```
DLR1+ZZ.P  # Implicit input
D          # Duplicate
 LR        # Push range(0, len(input))
   1+      # Add one to each
     ZZ    # Zip with the input
       .P  # Product of each pair
           # Implicit output, joined by J flag

```
> 1 votes

# Answer
# Brachylog v2, 6 bytes

```
i₁j₎w⊥

```

Try it online!

Half-port of Fatalize's v1 answer.

```
i₁        Choose a pair [element, 1-index] from the input.
  j₎      Replicate the element by its index.
    w     Print the result with no trailing newline.
     ⊥    Backtrack.

```
> 1 votes

# Answer
# Thunno 2 `J`, 3 bytes

```
dż×

```

Attempt This Online!

#### Explanation

```
dż×  # Implicit input           ->  "Why"
d    # Split into characters    ->  ["W","h","y"]
 ż   # Length range             ->  ["W","h","y"]  [1,2,3]
  ×  # Multiply together        ->  ["W","hh","yyy"]
     # Implicit output, joined  ->  "Whhyyy"

```
> 1 votes

# Answer
# PHP, 76 bytes

I'm sure this can be improved...

```
<?php for($i=0;$i<strlen($argv[1]);$i++)echo str_repeat($argv[1]{$i},$i+1);

```

Run from command line:

```
$ php [file] "Testing"

```
> 0 votes

# Answer
## Silicon(non-competing), 6 bytes

(This language is exactly the same age as this challenge, but I added some useful commands right after I saw it, so non-competing I think.)

```
biSÚÿj

```

Silicon uses CP037, which is a 255-bit codepage.

**Explanation:**

```
b        Push a space
i        Input
S        Split
Ú        Enumerate
ÿ        Replicate each list item n times
j        Join

```
> 0 votes

# Answer
# Javascript, 58 bytes

`e=a=>(Array.from(a).map((e,i)=>(e).repeat(i+1))).join("");`
> 0 votes

# Answer
# Java, 136 bytes

```
enum b{;public static void main(String[]a){int i=0,j=0;for(;i<a[0].length();i++){for(;j<i+1;j++)System.out.print(a[0].charAt(i));j=0;}}}

```

Takes input as program arguments.

Ungolfed with comments:

```
enum b {;
    public static void main(String[]a) {
        int i=0, j=0;                               // Init counters
        for (; i<a[0].length(); i++) {              // For each characters in string
            for (; j < i + 1; j++)                  // Loop from 0 to i
                System.out.print(a[0].charAt(i));   // Print character at i
            j=0;                                    // Reset j
        }
    }
}

```
> 0 votes

# Answer
# Jelly, 2 bytes

```
xJ

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---