title: Stretch the word

text:
# Question
Title: Stretch the word
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```
bonobo

```

Example output:

```
bonoobbooo

```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```
tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii

```

# Answer
# Jelly, 4 bytes

```
;\f"

```

Try it online!

### How it works

```
;\f"  Main link. Argument: S (string)

;\    Cumulatively reduce by concatenation.
      This yields the array of all prefixes of S.
  f"  Vectorized filter.
      Keep only occurrences of the nth letter in the nth prefix.

```
> 37 votes

# Answer
# Pyth, 6 bytes

Thanks to @Doorknob for taking off 1 byte.

Thanks to @Maltysen for taking off 5 bytes.

```
s@VQ._

```

Try it online!

## How it works

---

For example, take the string `"bonobo"`.

`._` makes a list: `['b', 'bo', 'bon', 'bono', 'bonob', 'bonobo']`

`VQ._` means "the preceding function vectorized (applied in parallel) over `Q` and `._`", which means `Q` (the input evaluated) will be treated as a list: `['b', 'o', 'n', 'o', 'b', 'o']`, and then they will be paired by the `@` like this:

```
     Q      ._         @ (intersect)
0:  'b'     'b'       'b'
1:  'o'     'bo'      'o'
2:  'n'     'bon'     'n'
3:  'o'     'bono'    'oo'
4:  'b'     'bonob'   'bb'
5:  'o'     'bonobo'  'ooo'

```

Therefore, `@VQ._` will produce `['b', 'o', 'n', 'oo', 'bb', 'ooo']`.

The `s` then joins them all together, creating a string `'bonoobbooo'`, which is then implicitly printed out to become `bonoobbooo`.
> 21 votes

# Answer
## Retina, ~~34~~ 19 bytes

*Saved 15 bytes by taking some inspiration from isaacg's solution.*

Byte count assumes ISO 8859-1 encoding.

```

$`¶
(\D)(?!.*\1¶)

```

The leading and trailing empty lines are significant.

Try it online!

### Explanation

```

$`¶

```

This is a replace stage which matches the empty regex (i.e. every zero-width position in the string) and substitutes `$`¶` for it, where `$`` is the prefix of the match and  inserts a linefeed. This basically computes all the prefixes and puts them on a separate line together with the last character of that prefix:

```
bb
obo
oboo
kbook
kbookk
ebookke
ebookkee
pbookkeep
ebookkeepe
rbookkeeper

```

There will be some leading and trailing linefeeds, but we can ignore them.

From each of these prefixes we want to keep the characters that are equal to the last character. For that we use another replace stage:

```
(\D)(?!.*\1¶)

```

This matches everything we *don't* want to keep and replaces it with a nothing. We match any character (using `\D` since we know there won't be digits in the input) and then make sure that there *isn't* another copy of that character at the end of the line.
> 14 votes

# Answer
## Python, 56 bytes

I seem to be stuck with two answers of the same length:

```
f=lambda x,*y:x and-~y.count(x[0])*x[0]+f(x[1:],x[0],*y)
f=lambda x,y=0:x[y:]and-~x[:y].count(x[y])*x[y]+f(x,y+1)

```

Edit: See @pacholik's answer for a shorter, alternative Python approach.
> 11 votes

# Answer
## Haskell, 39 bytes

```
f""=""
f x=f(init x)++filter(==last x)x

```

Usage example: `f "bonobo"` -\> `"bonoobbooo"`.

Different enough from @Damien's answer. Builds the string from the right by extracting all occurrences of the last character from the string and prepending a recursive call with all but the last character.
> 11 votes

# Answer
## JavaScript (ES6), ~~48~~ 45 bytes

```
s=>s.replace(n=/./g,c=>c.repeat(n[c]=-~n[c]))

```

Edit: Saved 3 bytes thanks to @user81655.
> 9 votes

# Answer
## \>\<\>, 27 bytes

```
>i:0g1+:\
:{-1v!?:<}o
/p${/

```

Requires the official interpreter which exits with an error when trying to print code point -1. Try it online!

The code reads input one char at a time and uses the first row of the codebox as a large array which stores the number of times each char has been seen so far (\>\<\> initialises non-program cells to 0). The second row is a loop for outputting a char multiple times.

Alternatively, here's a version which exits cleanly (37 bytes, not properly golfed):

```
>i:0(?;:0g1+:\
}o:{-1v!?:   <
v  p${<

```
> 9 votes

# Answer
# Haskell, ~~50~~ ~~42~~ 41 bytes

Saved 8 bytes thanks to Lynn

```
f t=[c|(i,c)<-zip[1..]t,x<-take i t,c==x]

```
> 8 votes

# Answer
# MATL, 8 bytes

```
tt!=RsY"

```

Try it online! Or verify all test cases at once.

### Explanation

```
t    % take input string implictly. Duplicate
t!   % duplicate and transpose into a column
=    % test for equality with broadcast. Gives an NxN array, where N is
     % input string length
R    % upper triangular part: set entries below the diagonal to 0
s    % sum of each column. For each postion in the input, gives how many
     % times that letter has appeared up to that position
Y"   % replicate elements (run-length decoding). Display implicitly

```
> 8 votes

# Answer
## Labyrinth, ~~54~~ 25 bytes

```
<#; "#: ={},>
 }=}(.);("@

```

Another collab with @MartinBüttner, who actually did ~~most~~ almost all of the golfing for this one. By revamping the algorithm, we've managed to cut down the program size by quite a bit!

Try it online!

### Explanation

A quick Labrinth primer:

* Labyrinth is a stack-based 2D language. There are two stacks, a main and auxiliary stack, and popping from an empty stack yields zero.
* At each junction, where there are multiple paths for the instruction pointer to move down, the top of the main stack is checked to see where to go next. Negative is turn left, zero is straight ahead and positive is turn right.

The two stacks of arbitrary-precision integers isn't much flexibility in terms of memory options. To perform the counting, this program actually uses the two stacks as a tape, with shifting a value from one stack to the other being akin to moving a memory pointer left/right by a cell. It's not quite the same as that though, since we need to drag a loop counter with us on the way up.

First off, the `<` and `>` on either end pop an offset and rotate the row of code that offset away by one either left or right. This mechanism is used to make the code run in a loop - the `<` pops a zero and rotates the current row left, putting the IP at the right of the code, and the `>` pops another zero and fixes the row back.

Here's what happens each iteration, in relation to the diagram above:

```
[Section 1]
,}    Read char of input and shift to aux - the char will be used as a counter
      to determine how many elements to shift

[Section 2 - shift loop]
{     Shift counter from aux
"     No-op at a junction: turn left to [Section 3] if char was EOF (-1), otherwise
      turn right
(     Decrement counter; go forward to [Section 4] if zero, otherwise turn right
=     Swap tops of main and aux - we've pulled a value from aux and moved the
      decremented counter to aux, ready for the next loop iteration

[Section 3]
@     Terminate

[Section 4]
;     Pop the zeroed counter
)     Increment the top of the main stack, updating the count of the number of times
      we've seen the read char
:     Copy the count, to determine how many chars to output

[Section 5 - output loop]
#.    Output (number of elements on stack) as a char
(     Decrement the count of how many chars to output; go forward to [Section 6]
      if zero, otherwise turn right
"     No-op

[Section 6]
}     Shift the zeroed counter to aux

[Section 7a]
This section is meant to shift one element at a time from main to aux until the main
stack is empty, but the first iteration actually traverses the loop the wrong way!

Suppose the stack state is [... a b c | 0 d e ...].

=     Swap tops of main and aux               [... a b 0 | c d e ...]
}     Move top of main to aux                 [... a b | 0 c d e ...]
#;    Push stack depth and pop it (no-op)
=     Swap tops of main and aux               [... a 0 | b c d e ...]
      Top is 0 at a junction - can't move
      forwards so we bounce back
;     Pop the top 0                           [... a | b c d e ... ]

The net result is that we've shifted two chars from main to aux and popped the
extraneous zero. From here the loop is traversed anticlockwise as intended.

[Section 7b - unshift loop]

#     Push stack depth; if zero, move forward to the <, else turn left
}=    Move to aux and swap main and aux, thus moving the char below (stack depth)
      to aux
;     Pop the stack depth

```
> 8 votes

# Answer
## Perl, 17

**(16 bytes code, +1 for -p)**

```
s/./${$&}.=$&/ge

```

### Usage:

```
perl -pe 's/./${$&}.=$&/ge' <<< 'bonobo'
bonoobbooo

```
> 7 votes

# Answer
# Pyth, 7 bytes

```
s@Led._

```

Test suite

*Test suite thanks to DenkerAffe*

Explanation:

```
s@Led._
     ._    All prefixes, implicitly applied to the input.
 @L        Filter each prefix for characters equal to
   ed      the last character of the prefix
s          Concatenate and implicitly print.

```
> 7 votes

# Answer
# Python 3, 52

```
def f(s):*s,x=s;return s and f(s)+x+x*s.count(x)or x

```
> 6 votes

# Answer
## PowerShell v2+, ~~52~~ 47 bytes

```
$b=@{};-join([char[]]$args[0]|%{"$_"*++$b[$_]})

```

Constructs an empty hashtable, stores it in `$b`. This is our "counter" of what letters we've seen. We then take input `$args[0]`, cast it as a char-array, and send it through a loop. Each iteration, we take the current character `"$_"` and multiply it by the pre-incremented counter at the given value, which will make the first occurrence be multiplied by `1`, the second by `2` and so on. We encapsulate that with a `-join` so it's all one word being output.

Saved 5 bytes thanks to TessellatingHeckler by using a hashtable instead of an array, so we didn't need to decrement the ASCII character by `97` to reach the appropriate index. This works because pre-incrementing the hash index implicitly calls `.Add()` in the background if that index doesn't exist, since hashtables are mutable.

```
PS C:\Tools\Scripts\golfing> .\stretch-the-word.ps1 tessellatingheckler
tessseelllattingheeeckllleeeer

```
> 5 votes

# Answer
# Dyalog APL, 6 bytes

```
∊,\∩¨⊢

```

TryAPL!

4 functions is an atop (2-train) of a fork (3-train):

```
┌──┴──┐
∊ ┌───┼─┐
  \   ¨ ⊢
┌─┘ ┌─┘
,   ∩

```

First  (right – a no-op) on the given string, giving `'bonobo'`

Then `,\` (concatenation scan) on the string, giving `'b' 'bo' 'bon' 'bono' 'bonob' 'bonobo'`

The two are forked together with (given as right and left arguments to) `∩¨` (intersection each), i.e. `('b'∩'b') ('bo'∩'o') ('bon'∩'n') ('bono'∩'o') ('bonob'∩'b') ('bonobo'∩'o')`, which is `'b' 'o' 'n' 'oo' 'bb' 'ooo'`

Finally,  (enlist) is applied to the result to flatten it, giving `'bonoobbooo'`

Hey, at least it matches Pyth! Obviously Jelly is shorter as it is a golf version of J, which in turn is an advanced 2-character-per-function dialect of APL.
> 5 votes

# Answer
# Pyth, 11 bytes

```
s.e*b/<Qhkb

```

Try it here!

## Explanation

```
s.e*b/<Qhkb    # Q = input

 .e            # map over input with b as value and k as index (Q get appended at the end inplicitly)
      <Qhk     # take the first k+1 chars of Q
     /    b    # count occurences of b in there
   *b          # repeat b that many times
s              # join resulting list into one string

```
> 4 votes

# Answer
# 05AB1E, 10 bytes

Code:

```
$vy«Dy¢y×?

```

Explanation:

```
$           # Push the number 1 and input
 v          # Map over the input string
  y«        # Concat the letter to the previous string (initial 1)
    D       # Duplicate this string
     y¢     # Count the occurences of the current character in the string
       y×   # Multiply this number with the current character
         ?  # Pop and print without a newline

```

Uses the **CP-1252** encoding. Try it online!
> 4 votes

# Answer
## J, 11 bytes

```
#~+/@(={:)\

```

This is a monadic verb. Try it here. Usage:

```
   f =: #~+/@(={:)\
   f 'tutu'
'tuttuu'

```

## Explanation

```
#~+/@(={:)\
     (   )\  For each non-empty prefix:
       {:      Take last element,
      =        compare for equality to the others and itself
  +/@          and take sum (number of matches).
#~           Replicate original elements wrt the resulting array.

```
> 4 votes

# Answer
# CJam, 14

```
q:A,{)A<_)--}/

```

Try it online

**Explanation:**

```
q:A      read the input and store in A
,        get the string length
{…}/     for each number from 0 to length-1
  )      increment the number
  A<     get the prefix of A with that length
  _      duplicate it
  )      separate the last character
  -      remove it from the rest of the prefix
  -      remove all the remaining characters (different from the last one)
          from the prefix

```
> 3 votes

# Answer
# Perl 6, 37 bytes

```
{.split('').map({$_ x++%.{$_}}).join}

```
> 2 votes

# Answer
# PHP, ~~54~~ ~~51~~ ~~50~~ 47 bytes

```
for(;$C=$argn[$X++];)echo str_repeat($C,++$$C);

```

Run like this:

```
echo abracadabra | php -nR 'for(;$C=$argn[$X++];)echo str_repeat($C,++$$C); echo"\n";'

```

## Tweaks

* Saved 3 bytes by using variable variables. Changed used variables to uppercase to prevent collision
* Saved a byte by removing type cast `null` to `int` for string offset, as string offset is cast to int anyway
* Saved 3 bytes by using `$argn` instead of `$argv` (thx Titus)
> 2 votes

# Answer
# \>\<\>, 52 bytes

```
i:0(?;&l:?!v1-$:&:&=?\}70.>
6f+0.00o:&~/         \:o

```

It stacks every letter read, prints them once and once again for every similar letter in the stack.
It uses the `&` register, because having to handle 3 variables on the stack (current read letter, position in the stack, letter at this position) is a pain.

You can try it here!
> 2 votes

# Answer
# Rust, 176 Bytes

```
fn s(w:&str)->String{let mut m=std::collections::HashMap::new();w.chars().map(|c|{let mut s=m.remove(&c).unwrap_or(String::new());s.push(c);m.insert(c,s.clone());s}).collect()}

```

This uses a map to store a string for every character in the input. For each character, the string will be removed from the map, concatenated with the character, inserted back into the map and appended to the output.

I would have liked to use `get(...)` instead of `remove(...)`, but the borrow checker had me change my mind.
> 2 votes

# Answer
# Javascript ES6 44 bytes

```
q=>q.replace(/./g,a=>x[a]=(x[a]||'')+a,x=[])

```

---

old answer

Javascript ES6 46 bytes

```
q=>(x=[...q]).map(a=>x[a]=(x[a]||'')+a).join``

//thanks user81655 for -1 byte

```
> 2 votes

# Answer
# Mathcad, 66 bytes

Unfortunately, Mathcad doesn't have particularly good string handling, so I've converted the input string to a vector and then used a (character code indexed) vector to keep track of the number of times a character is encountered, adding the character that number of times to a result vector. Finally, the result vector is converted back to a string. Quite lenghty unfortunately.

Note that Mathcad uses a 2D "whiteboard" interface, with a mix of normal text and operators; operators are normally entered via a toolbar or keyboard shortcut; for example, ctl-# enters the for loop operator, which comprises the keyword for, the element-of symbol and 3 empty "placeholders" for the iteration variable, range and body expressions respectively. Typing \[ after a variable name enters array index mode, Typing ' enters a matched pair of parentheses (*mostly ... there are exceptions depending upon what else is in the surrounding expression*)
> 2 votes

# Answer
# Ruby, 35 bytes

```
->s{s.gsub(/./){$&*-~$`.count($&)}}

```

It's an anonymous function using regex and some magical variables. Usage:

```
->s{s.gsub(/./){$&*-~$`.count($&)}}["bonobo"]
=> "bonoobbooo"

```
> 2 votes

# Answer
# Julia, ~~38~~ 35 bytes

```
!s=[]==s?s:[!s[1:end-1];s∩s[end]]

```

I/O is in the from of character arrays. Try it online!

### How it works

We (re)define the monadic operator **!** for our purposes.

When **!** is called, it checks if its argument **s** is empty. If it is, it returns its argument.

If **s** is non-empty, we intersect **s** with its last character (`s[end]`), which yields all occurrences of that character in **s**. This result is concatenated with the return value of a recursive call to **!** with **s** minus its last character (`s[1:end-1]`) as argument.
> 2 votes

# Answer
## Mathematica, 57 bytes

```
StringReplace[Clear@c;c@_=0;#,x_:>x~StringRepeat~++c[x]]&

```

We use `c[x]` as a lookup table of how often character `x` has already occurred. This is incremented each time it's retrieved in `x~StringRepeat~++c[x]`. Unfortunately, to make the function reusable, we need to reset the lookup table each time with `Clear@c;c@_=0;`, which is quite expensive.
> 1 votes

# Answer
# awk, 72 bytes

```
BEGIN{FS=""}{for(i=1;i<=NF;i++){a[$i]++;for(j=0;j<a[$i];j++)printf $i}}

```

The idea is to store the count of the appearing character in an associative array and print the character this count times.
> 1 votes

# Answer
## Python, ~~66~~ 62 bytes

Try it here

### Golfed

```
def s(w,o=[],n=""):
 for x in w:o+=x;n+=x*o.count(x)
 return n

```

### Ungolfed

```
def stretch(word):
    occurrences = []
    newWord = ""
    for w in word:
        occurrences.append(w)
        newWord += w * occurrences.count(w)
    return newWord

```
> 1 votes

# Answer
# Beam, 32 ~~33~~ ~~42~~ bytes

This should have been smaller, but I lost some bytes initializing the memory slots to 0. Swapping some flow directions managed to eliminate a lot of empty space.

```
 >+\
vus/
>rnH
  >g'\
(@v's/
^`<

```

Try it in this snippet

General explanation.

* Set all the memory slots from 0-255 to 0
* Read in the input ascii value into the beam
* If beam is 0 halt (beam = store)
* Get the memory\[beam\] value into the store, increment it and save back
* Decrement the store to 0 printing out the beam character
* Repeat
> 1 votes

# Answer
# BQN, ~~7~~ 6 bytes

```
⊢/˜1+⊒

```

Anonymous tacit function. Try it at BQN online!

### Explanation

```
⊢/˜1+⊒
     ⊒   For each character, how many times has it appeared previously?
   1+    Add 1 to each
 /˜      Replicate that many times the elements of
⊢        The original input

```
> 1 votes

# Answer
# Vyxal `sr`, 4 bytes

```
¦¨£↔

```

Try it Online!
> 1 votes

# Answer
# Knight, 77 bytes

```
;=x=yP;Wx;E++"=x"A Ax" 0"=xSxF1""Wy;E++++"O+*A Ay=x"=aA Ay"+1x"a"'\'"=ySyF1""

```

Try it online!

Ungolfed:

```
; = x (= y PROMPT)
; WHILE x
    ; EVAL (+ (+ "=x" (ASCII (ASCII x))) " 0")
    : = x (SUBSTITUTE x 0 1 "")
: WHILE y
    ; EVAL (+ (+ (+ (+ "O+*A Ay=x" (= a (ASCII (ASCII y)))) "+1x") a) "'\'")
    : = y (SUBSTITUTE y 0 1 "")

```
> 1 votes

# Answer
# Ruby, ~~50~~ 48 bytes

Anonymous function.

```
->s{i=0
s.chars.map{|c|c*s[0,i+=1].count(c)}*''}

```
> 0 votes

# Answer
# Go, 142 bytes

No awards, but a neat exercise.

```
import(."fmt"
."strings")
func f(s string){m:=map[rune]int{}
for _,c:=range s{if _,ok:=m[c];!ok{m[c]=1}
Print(Repeat(string(c),m[c]))
m[c]++}}

```

You can save 1 byte by changing `for _,c` to `for i,c` and changing `string(c)` to `s[i:i+1]`, but then it works only with ASCII.
> 0 votes

# Answer
# Factor, 120 bytes

```
[ dup dup length iota [ head* ] with map reverse zip [ first2 over [ = ] curry count swap <array> >string ] map concat ]

```

Ungolfed, explained:

```
! "bonobo" -> { "b" "bo" "bon" "bono" "bonob" "bonobo" }
: ascend-string ( string -- string ascending-seq )
    dup dup length iota [ head* ] with map reverse ;

: stretch-word ( string -- stretched )
    ascend-string zip        ! zip string with ascending version of itself
    [
        first2 over          ! get each string index and its ascended version
        [ = ] curry count    ! count how many times this letter has appeared
        swap <array> >string ! >string
    ] map concat ;           ! "" join

```

Translation of: @KennyLau's Pyth answer.
> 0 votes

# Answer
# Java 10, ~~220~~ 94 bytes

```
s->{var m=new int[123];for(var c:s.toCharArray())for(int i=++m[c];i-->0;System.out.print(c));}

```

Try it online.

**Explanation:**

```
s->{                   // Method with String parameter and no return-type
  var m=new int[123];  //  Integer-array containing 123 zeros
  for(var c:s.toCharArray())
                       //  Loop over the characters of the input-String
    for(int i=++m[c];  //   Increase the count of the current character in the array first,
                       //   and set `i` to this count
        i-->0;         //   Inner loop that many times
      System.out.print(c));}
                       //    And print that many times the current character `c`

```
> 0 votes

# Answer
# Swift, 134 bytes

```
var c = NSCountedSet(),n = ""
i.characters.forEach({var s = String($0);c.addObject(s);for _ in 0..<c.countForObject(s){n.append($0)}})

```

Assumes Foundation has been implicitly imported. `i` is the input of type `String`, `n` is the output of type `String`.

I'm falling back on Foundation classes here as `NSCountedSet` gives the the character count lookup behavior we want. The problem with mixing Swift and Objective-C types is that Swift structs do not conform to `NSObjectProtocol`. We see this issue when trying to store a Swift `Character` (`String.CharacterView`) in an `NSCountedSet`, which is expecting objects of type `AnyObject` (or `NSObject`). I lose around 17 bytes having to create a `String` from each `Character` in the input string.

I also lose some bytes having to create a `for` loop to append the new characters based on their count in the set. I can't use `forEach` here since the return type of `countForObject` is an `Int`, not a collection type. There is room for improvement here.

Swift `String` types are immutable, so I can't explicitly mutate the input. There may be room for improvement by using an `NSMutableString`, but the characters lost by explicitly declaring the input of that type and calling the `appendString` method may add more characters to the program.
> 0 votes

# Answer
# PHP, 46 bytes

```
for(;--$X||($C=$argn[$K++])&&$X=++$$C;)echo$C;

```

Run as pipe with `-nR` or try it online.

These 42 bytes print the same, but the loop is infinite (which results in a timeout error):

```
for(;--$X||$X=++${$C=$argn[$K++]};)echo$C;

```

---

printf solution, 47 bytes:

```
for(;$C=$argn[$K++];)printf("%'$C".++$$C.s,"");

```

Side note: PHP used to yield notices for undefined constants and cast them to string for decades. PHP 7.2 yields warnings with a hint that, in future versions, they will throw fatal errors.

End of an era. :-/ I wonder if they will do the same to undefined variables.
> 0 votes

# Answer
# Kotlin, 60 bytes

```
{s:String->s.fold(""){a,c->a+"$c".repeat(a.count{it==c}+1)}}

```

Try it online!
> 0 votes

# Answer
# brev, 46 bytes

```
(with(ct*'a 0)(as-list flatten(over(it x x))))

```

If output like `("m" "i" "s" "ss" "ii" "sss" "ssss" "iii" "p" "pp" "iiii")` were legal you could cut out the as list flatten for seventeen bytes.
> 0 votes

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


title: Fill in the Blanks, Please!

text:
# Question
Title: Fill in the Blanks, Please!
(No, not this nor any of these)

Given a string and a list of strings, fill in the all blanks in the input string with corresponding strings.

## Input/Output

The input string contains only alphabetic characters, spaces, and underscores. It is nonempty and does not start with an underscore. In other words, the input string matches the regex `^[a-z A-Z]([a-z A-Z_]*[a-z A-Z])?$`

Every string in the input list is nonempty and contains only alphanumeric characters and spaces. In other words, they match the regex `^[a-z A-Z]+$`.

A blank is a contiguous sequence of underscores (`_`) which is neither preceded nor proceeded by an underscore.

The input string contains `n` blanks for some positive integer `n`, and the list of strings contains exactly `n` strings.

The output is obtained by replacing each `k`-th blank in the input string by the `k`-th string in the input list of strings.

## Example

Given an input string `"I like _____ because _______ _____ing"` and a list of strings `["ice cream", "it is", "satisfy"]`, we can find the output as follows:

* The first blank comes directly after `"like "`. We fill that in with `"ice cream"` to get `"I like ice cream because ______ _____ing"`.
* The second blank comes directly after `"because "`. We fill that in with `"it is"` to get `"I like ice cream because it is _____ing"`.
* The third blank comes directly after `"is "`. We fill that in with `"satisfy"` to get `"I like ice cream because it is satisfying"`.

We output the final string `"I like ice cream because it is satisfying"`.

## Test Cases

```
input string, input list => output
"Things _____ for those who ____ of how things work out _ Wooden",["work out best","make the best","John"] => "Things work out best for those who make the best of how things work out John Wooden"
"I like _____ because _______ _____ing",["ice cream","it is","satisfy"] => "I like ice cream because it is satisfying"
"If you are ___ willing to risk _____ you will ha_o settle for the ordi_____Jim ______n",["not","the usual","ve t","nary ","Roh"] => "If you are not willing to risk the usual you will have to settle for the ordinary Jim Rohn"
"S____ is walking from ____ to ____ with n_oss of ___ W_____ Churchill",["uccess","failure","failure","o l","enthusiasm","inston"] => "Success is walking from failure to failure with no loss of enthusiasm Winston Churchill"
"If_everyone_is_thinking ____ ____ somebody_isnt_thinking G____e P____n",[" "," "," ","alike","then"," "," ","eorg","atto"] => "If everyone is thinking alike then somebody isnt thinking George Patton"
"Pe_________e __say ____motivation does__ last Well___her doe_ bathing____thats why we rec____nd it daily _ __________lar",["opl","often ","that ","nt"," neit","s","  ","omme","Zig","Zig"] => "People often say that motivation doesnt last Well neither does bathing  thats why we recommend it daily Zig Ziglar"

```

# Answer
# Convex, 5 bytes

```
'_%.\

```

Try it online!

Convex is a CJam-based language, and this answer is almost the same as my CJam answer, except for `l~` which is unneeded here, since Convex does automatic argument evaluation at the start of the program.

Explanation:

```
'_%.\ e# Full program only
'_    e# Push '_'
  %   e# Split and remove empty chunks
   .\ e# Vectorize by Swap

```
> 5 votes

# Answer
# Japt, 8 bytes

```
r"_+"@Vv

```

Test it online!

I feel I missed some hidden catch in the rules because this is extremely simple: "replace each run of underscores in the string with the next item in the array."
> 4 votes

# Answer
# JavaScript, 35 bytes

```
a=>b=>a.replace(/_+/g,a=>b.shift())

```

Try it online
> 3 votes

# Answer
# Ruby, 28 + 1 = 29 bytes

```
$_=gsub(/_+/){|i|gets[/.*/]}

```

Uses `-p`

The first line is the format string, the rest of the lines are the array.

Try it online!
> 2 votes

# Answer
# Proton, 42 bytes

```
a=>b=>re.sub("_+",_=>b.pop(0),a)
import re

```

Try it online!

Stupid imports...

Same thing in python:

# Python 3, 53 bytes

```
lambda a,b:re.sub("_+",lambda _:b.pop(0),a)
import re

```

Try it online!
> 2 votes

# Answer
# MATL, 9 bytes

```
'_+'i1&YX

```

**Try it online!**

### Explanation

```
'_+'   % Push this string: regexp pattern
i      % Input cell array of replacement strings
1      % Push 1
&YX    % Four-input regexp replacement. This implicitly inputs the original
       % string, and consecutively replaces each first occurrence of the
       % regexp pattern in that string by one of the replacement strings.
       % Implicitly display

```
> 2 votes

# Answer
# Jelly, ~~8~~ 7 bytes

```
ṣ”_¬Ðfż

```

Try it online! Edit: Saved 1 byte thanks to @Erik the Outgolfer. Explanation:

```
ṣ”_         Split on underscores
   ¬Ðf      Discard empty values
      ż     Zip with second input
            Implicit concatenated output

```
> 2 votes

# Answer
# CJam, 7 bytes

```
l~'_%.\

```

Try it online!

-1 thanks to a clever trick by Martin Ender.

Explanation:

```
l~'_%.\ e# Full program only
l       e# Input line
 ~      e# Eval
  '_    e# Push '_'
    %   e# Split and remove empty chunks
     .\ e# Vectorize by Swap

```
> 2 votes

# Answer
# Python 2, 61 bytes

```
import re
s,l=input()
for i in l:s=re.sub('_+',i,s,1)
print s

```

Try it online!

Damn.

## Python 2, 63 bytes

```
import re
f=lambda s,l:l and f(re.sub('_+',l[0],s,1),l[1:])or s

```

Try it online!
> 1 votes

# Answer
# Perl 5, 25 + 1 (-p) = 26 bytes

```
@a=eval<>;s|_+|shift@a|eg

```

Try it online!
> 1 votes

# Answer
# Pyth, 10 bytes

```
s.i:E"_+"3

```

**Try it here!**

# How it works?

```
s.i:E"_+"3   Full program.

   :E    3   Split the second input on matches of the regex...
     "_+"    The regex "_+" (matches 1 or more underscores)
 .i          Interleave the elements of the split list with the input.
s            Join to a string.

```
> 1 votes

# Answer
# RProgN 2, 11 bytes

```
x='_+'³[x‘r

```

Takes a string and a stack of strings on the top of the stack.

The first (top) element of a stack is to the right, hence input is right to left.

## Explained

```
x='_+'³[x‘r
x=          # Set the stack of replacements to x
  '_+'³   r # Replace each chunk of _'s with the function...
       [    # Pop off the group of _'s
        x‘  # Pop the top element off x. Use that.

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 12 bytes

```
„__¤:sv'_y.;

```

Try it online!

**Explanation**

```
„__¤:          # replace all runs of multiple "_" with a single "_"
     sv        # for each y in the list of replacements
       '_y.;   # replace the first instance of "_" with y

```
> 1 votes

# Answer
# Java 8, 57 bytes

```
a->s->{for(String i:a)s=s.replaceFirst("_+",i);return s;}

```

When I read the challenge I at first thought we should make a grammatically correct sentence with the words being in random order, but just replacing lines with each sequential word is easier. ;)

**Explanation:**

Try it here.

```
a->s->{            // Method with String-array and String parameter and String return-type
  for(String i:a)  //  Loop over the input-array
    s=s.replaceFirst("_+",i);
                   //   Replace the first line (1 or more adjacent "_") with the substring
                   //  End of loop (implicit / single-line body)
  return s;        //  Return the result
}                  // End of method

```
> 1 votes

# Answer
# C# (.NET Core), ~~97~~ 96 + 18 bytes

Saved 1 byte thanks to **Kevin Cruijssen**!

The 18 bytes are for using `System.Linq`.

```
s=>l=>string.Concat(s.Split('_').Where(x=>x!="").Zip(l.Concat(new[]{""}),(x,y)=>x+y).ToArray());

```

Try it online!
> 1 votes

# Answer
# Python 2, 49 bytes

```
s,l=input();import re;print re.sub("_+","%s",s)%l

```

Try it online!

The list input is taken as a tuple. Allowing actual lists as input would add another seven bytes, as a conversion would be required (`tuple(...)`).
> 1 votes

# Answer
# Vyxal `s`, 6 bytes

```
\_/';Y

```

Try it Online!

Look Ma, no Unicode!

```
\_/    # Split on underscores
   ';  # Filter out empty strings
     Y # Interleave with fill-in values
       # (s flag) concatenate the top of stack

```
> 1 votes

# Answer
# Factor, 34 bytes

```
[ R/ _+/ "%s"re-replace vsprintf ]

```

Try it online!

* `R/ _+/ "%s"re-replace` Replace any amount of contiguous underscores with `%s`.
* `vsprintf` Interpolate a sequence of strings into another string at every `%s`.
> 1 votes

# Answer
# Regex (RE2 or better), 23 bytes

```
s/_+(.*?)`([^`]*)/$2$1/

```

Try it online! \- RE2
Try it online! \- ECMAScript
Try it online! \- Perl
Try it online! \- PCRE2
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby

This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, where necessary or convenient). (See also the single-pass version.)

Input is taken as the string with blanks followed by the full list of string arguments, each delimited by ```.

```
s/          # Begin substitution - match the following:
_+          # Match an entire blank
(.*?)`      # $1 = everything subsequent, up until but not including the first
            #      "`" delimiter; consume the delimiter
([^`]*)     # $2 = a string argument, captured up to but not including the next
            #      "`" delimiter; the ".*?" version would be "(.*?)(?=`|$)"
/           # Replace with the following:
$2$1        # "_+" is replaced with $2, and $1 is preserved, but the original
            # $2 is deleted.
/           # No flags - match and replace just once

```

# sed `-E`, 31 bytes

```
:a
s/_+([^`]*)`([^`]*)/\2\1/
ta

```

Try it online!

sed lacks lazy quantifiers, so `([^,]*),` must be used instead of `(.*?),` costing +2 bytes.
> 1 votes

# Answer
# Regex (.NET), 46 bytes

```
s/_+(?<=((?=.*?(\2?`([^`]*)))_+.*?)*)|`.*/$3/g

```

Try it on regex101! \- .NET

Input is taken as the string with blanks followed by the full list of string arguments, each delimited by ```.

This is a single regex substitution, to be applied once. (See also the looped version.)

As such, for each individual match it must count how many blanks are to the left of the current one being replaced, because separate matches in a `/g`lobal match or replace operation cannot communicate to each other (there is no persistent state between matches, other than the current position in the string). Variable-length lookbehind is used for this, with group-building to count string arguments in parallel with counting blanks. (I tried using balancing groups for the counting instead, and that took a bit more bytes.)

```
s/                       # Begin substitution - match the following:
    _+                       # Match an entire blank
    (?<=                     # Lookbehind – evaluated right-to-left, so read
                             # from the bottom up, until entering the lookahead,
                             # then read normally again.
        # When the below loop has finished, $3 will contain the string argument
        # of an index corresponding to the index of the blank matched above.
        (
            (?=              # Lookahead
                .*?          # Skip a minimal number of characters in order to
                             # match the following:
                (            # \2 = the following:
                    \2?      # Previous value of \2, if set
                    `        # Match a delimiter
                    ([^`]*)  # $3 = the next string argument (read up to but
                             #      not including the next delimiter, if any)
                )
            )
            _+               # Match an entire blank
            .*?              # Skip a minimal number of characters in order to
                             # match the above (since no backtracking will
                             # occur, they will all be non-underscores).
        )*                   # Iterate the above as many times as possible –
                             # for each blank matched (going right to left),
                             # \2 is appended with another string argument
                             # (going left to right).
    )
|                            # or...
    `.*                      # Match the entire list of string arguments,
                             # including first delimiter, to be deleted. This
                             # can only be matched after the first stage,
                             # above, has finished.
/                        # Replace with the following:
$3                           # The captured string argument
/                        # Flags:
g                            # Global – replace all matches in one sweep from
                             # left to right.

```

# Regex (Python`regex`), 54 bytes

```
s/_+(?<=((?=.*?(?=(\3?))(\2`([^`]*)))_+.*?)*)|`.*/\4/g

```

Try it online! \- Python `import regex`

A port of the .NET version. The captures `\2` and `\3` are copied back and forth to avoid use of nested backreferences, which Python doesn't support.

# Regex (PCRE2 v10.35+), 96 bytes

`s/_+(?*(.*`(.*)(.*$)))((?<=(?=^(?>.*?_+(?=[^`]*(\5?+`[^`]*)))+(?=\1)[^`]*\5\3$|(?4)).))|`.*/$2/g`

Try it on regex101!
Attempt This Online!

This version emulates variable-length lookbehind using recursion with fixed-length lookbehind. But since capture groups cannot be returned from a subroutine call, the regex must make a guess as to what the subroutine call will return; this is done using `(?*`...`)` non-atomic lookahead. If the recursive call detects a mismatch between the guess and the actual result, it returns a non-match, forcing the non-atomic lookahead to try other guesses until one matches.
> 1 votes

# Answer
# K (ngn/k), 27 bytes

```
{(*c),/y,'1_c:(~#:')_"_"\x}

```

Try it online!

Splitting based on "runs of underscores" seems longer than splitting by single underscores and removing empty strings.

```
{(*c),/y,'1_c:(~#:')_"_"\x}  x: string, y: substitution list
                     "_"\x    split by single underscores
              (~#:')_         remove empty strings
            c:                call it c
       y,'1_    zipped concatenate with c, head removed to match lengths
 (*c),/         join them and add back the head of c

```
> 1 votes

# Answer
# PowerShell Core, 46 bytes

```
param($a,$b)-join($a-split'_+'|%{$_
$b[$i++]})

```

Try it online!
> 1 votes

# Answer
# Raku, 24 bytes

```
->$_,\s{S:g[_+]=s.shift}

```

Try it online!

Replace and shift, like many answers.
> 1 votes

# Answer
# brev, ~~36~~ 28 bytes

Original attempt:

```
(fn(fold(fn(strse y"_+"x 1))x rest))

```

Wait, this works for 28:

```
(fn(strse x"_+"(pop! rest)))

```

Brev usually does poorly on here but since it was inspired by Snobol, I was happy to beat it.
> 1 votes

# Answer
# Stacked, 21 bytes

```
[@y'_+'[y shift]repl]

```

Try it online!

Replaces all runs of `_` with `y shift`. Nothing original, as it seems.
> 0 votes

# Answer
# SOGL V0.12, 7 bytes

```
lΔ╔*№≤ŗ

```

Try it Here!

Explanation:

```
l        get the strings length
 Δ       range
  ╔*     multiply an underscore with each of the numbers
    №    reverse vertically (so the longest underscores get replaced first)
     ≤   put the array on top - order parameters for ŗ correctly
      ŗ  replace in the original string each any occurence of the underscores with its corresponding item in the array

```
> 0 votes

# Answer
# Nim, 73 bytes

```
import pegs,sugar
proc f(s,b:auto):auto=s.replace peg"'_'*",(i,x,y)=>b[i]

```

Try it online!
> 0 votes

# Answer
# Jelly (fork), 5 bytes

```
œṢ”_ż

```

Try it online! (or rather, don't, as this is a fork, not on TIO)

Full program, as we abuse Jelly's smash-printing.

## How it works

```
œṢ”_ż - Main link. Takes a string S and a list of fillers F
œṢ    - Split S on runs of:
  ”_  -   Underscores
    ż - Zip with the fillers, and smash-print

```
> 0 votes

# Answer
# Haskell, 61 bytes

```
s#(w:r)|(p,n)<-span(/='_')s=p++w++(snd$span(=='_')n)#r;s#[]=s

```

Try it online!
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 51 bytes

```
	I =INPUT
R	I SPAN('_') =INPUT	:S(R)
	OUTPUT =I
END

```

Try it online!
> 0 votes

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


title: History homework helper

text:
# Question
Title: History homework helper
Doing my history reading and note-taking, I can't help but get tired of writing out all these long dates –– 1784 is six entire pencil lifts! jǝǝz!

As you can see, I –– like most challenge posters on this site –– am lazy when it comes to writing stuff. Thus, I ask you to please help me shorten some dates. Of course, your solution must be as short as possible since my hand is already tired from writing typing out the test cases.

**How do I shorten a date?**

Well funny you should ask. It's fairly simple:

1. Take two integers as input in whatever order you want (`(smallest, biggest)` or `(biggest, smallest)`).
2. Take the larger of the two numbers, and take only the part not in the smaller number.
For example, given `2010, 2017`, shorten `2017` to `-7` because `201_` is in both at the same digit-places.
3. Print or return the smaller number, followed by a dash and then the shortened larger number.

**For example:**

```
Bonus brownies for you if you figure out these dates' significance :)
1505, 1516 -> 1505-16
1989, 1991 -> 1989-91
1914, 1918 -> 1914-8
1833, 1871 -> 1833-71
1000, 2000 -> 1000-2000
1776, 2017 -> 1776-2017
2016, 2016 -> 2016-

These dates lack significance :(
1234567890, 1234567891 -> 1234567890-1
600, 1600 -> 600-1600
1235, 1424 -> 1235-424
600, 6000 -> 600-6000

```

# Answer
# 05AB1E, 16 bytes

```
`R¹íζ€Ë1Üg£R‚'-ý

```

Try it online!

Uses Jonathan Allan's algorithm.
> 1 votes

# Answer
# Jelly,  ~~17~~  16 bytes

```
DUµn/TṪṁ@Ṫ,j”-FṚ

```

A full program taking a list of years `from, to` and printing the result.

**Try it online!** or see the test suite.

### How?

```
DUµn/TṪṁ@Ṫ,j”-FṚ - Main link: list of years [from, to]    e.g [1833,1871]
D                - convert to decimals                        [[1,8,3,3],[1,8,7,1]]
 U               - upend (to cater for differing lengths)     [[3,3,8,1],[1,7,8,1]]
  µ              - monadic chain separation, call that V
    /            - reduce V with:
   n             -   not equal?                               [1,1,0,0]
     T           - truthy indices                             [1, 2]
      Ṫ          - tail                                       2
         Ṫ       - tail V (pop from & modify V)               [1,7,8,1]
       ṁ@        - mould (swap @rguments) V like that length  [1,7]
          ,      - pair that with (the modified) V            [[1,7],[[3,3,8,1]]
            ”-   - literal '-' character
           j     - join                                       [1,7,'-',[3,3,8,1]]
              F  - flatten                                    [1,7,'-',3,3,8,1]
               Ṛ - reverse                                    [1,8,3,3,'-',7,1]
                 - implicit print                             1833-71

```
> 5 votes

# Answer
# Javascript ES6, ~~59~~ 57 chars

```
(x,y)=>(x+'-'+y).replace(x*10>y?/^((.*).*-)\2/:/()/,"$1")

```

Test:

```
f=(x,y)=>(x+'-'+y).replace(x*10>y?/^((.*).*-)\2/:/()/,"$1")

console.log(`1505, 1516 -> 1505-16
1989, 1991 -> 1989-91
1914, 1918 -> 1914-8
1833, 1871 -> 1833-71
1000, 2000 -> 1000-2000
1776, 2017 -> 1776-2017
2016, 2016 -> 2016-
1234567890, 1234567891 -> 1234567890-1
600, 1600 -> 600-1600
1235, 1424 -> 1235-424`.split`
`.map(t => t.match(/(\d+), (\d+) -> (.*)/)).every(([m,x,y,key]) => f(x,y)===key || console.log(x,y,key,f(x,y))))
console.log(f(600,6000))
```
> 3 votes

# Answer
# Dyalog APL, 29 bytes

```
{⍺,'-',x/⍨⌈\~((-⍴x)↑⍕⍺)=x←⍕⍵}

```

Try it online!

**How?**

`⍺,'-'` \- the first year + `, -`

`=x←⍕⍵` \- compare the second year formatted

`((-⍴x)↑⍕⍺)` \- to the first year padded with spaces from left

`⌈\~` \- negate the result and mark all 1s after the first

`x/⍨` \- take the second year in all marked position
> 1 votes

# Answer
# Retina, 34 bytes

```
(.*)((.)*),\1((?<-3>.)*)\b
$1$2-$4

```

Try it online! Link includes test cases. The balancing group and the word boundary ensure that both numbers are the same length before the prefix is matched. If not, then the word boundary matches at the start of the second year, so all that happens is that the comma changes to a dash.
> 1 votes

# Answer
# Python 2, 102 bytes

```
lambda s,n:`s`+'-'+[[`n`[i:]for i in range(len(`s`)+1)if `n`[:i]==`s`[:i]][-1],`n`][len(`n`)>len(`s`)]

```

Try it online!

I feel like there has to be a better way to do this since it seems really verbose. Extreme abuse of the \`\` evaluation of variables for this to work since we can't take strings as input.
> 1 votes

# Answer
# Haskell, 92 bytes

```
f=q.map show;q[a,b]=a++"-"++if(1<$a)<(1<$b)then b else snd<$>(snd$span(uncurry(==))$zip a b)

```

Takes input as a list of two integers \[earlier date, later date\].

Try it online!
> 1 votes

# Answer
## Python 2, 127 bytes

I am still new to this, so I don't know if it is okay to place another answer in the same language. Since I can't comment on other peoples posts yet I take my chances here.

* Is it allowed to change the input from Integer to String? Cause that would save me around 10 bytes.
* Arnlod Parmers answer has a mistake on 1989, 1991. (during the time I am posting this). Thank you tho for the \`\` evaluation trick tho (it saved me a byte)!

```
def f(s,b):
 s=`s`+'-'
 if len(`b`)>=len(s):return s+`b`
 for i in range(len(`b`)):
    if s[i]!=`b`[i]:return s+`b`[i:]
 return s

```

Try it online!

What I do is, I compare each single digit from both times and if the bigger one varies I print the smaller number plus the rest of the bigger one.

If someone could help me golf out the third line I would save like 30+ bytes. I only implemented it to handle the case of 600,6000 where the digits are equal but not the same length.
> 0 votes

# Answer
# Haskell, 143 bytes

```
g x y=h(show x)(show y)
h x y=x++"-"++if length x<length y then y else foldl(\a(c,d)->if a==[]then if c==d then[]else[d]else a++[d])[](zip x y)

```

Try it online!

`smallest biggest` input (integers).

`if length x<length y then y` means that if `x` has less digits than `y` then the common part is void. Else, we store the digits of `y` from the first different digit.
> 0 votes

# Answer
## C++, ~~285~~ 271 bytes

-14 bytes thanks to Zacharý

```
#include<iostream>
#include<string>
#define S s.size()
#define R r.size()
using namespace std;void h(int a,int b){auto r=to_string(a),s=to_string(b);if(R>S)s=string(R-S,' ')+s;if(S>R)r=string(S-R,' ')+r;int i=0;for(;i<R;++i)if(r[i]!=s[i])break;cout<<a<<'-'<<s.substr(i);}

```

Code for testing :

```
std::vector<std::pair<int, int>> test = {
    {1505,1516},
    {1989,1991}, //End of the cold war
    {1914,1918}, //First world war start and end
    {1833,1871},
    {1000,2000}, //2000 = Y2K bug, 1000 is... well... Y1K bug ? :)
    {1776,2017}, //US constitution signed the 4th july, French elections & year of the C++ 17 standard
    {2016,2016}, //US elections
    {1234567890,1234567891},
    {600,1600},
    {1235,1424},
    {600,6000}
};

for (auto&a : test) {
    h(a.first, a.second);
    std::cout << '\n';
}

```
> 0 votes

# Answer
# Python 2, ~~89~~ 88 bytes

```
lambda a,b:`a`+'-'+`b`[map(lambda c,d:(len(`a`)==len(`b`))*(c==d),`a`,`b*10`).index(0):]

```

Try it online!
> 0 votes

# Answer
# Common Lisp, 120 bytes

```
(lambda(s b &aux(d(#1=format()"~a"b)))(#1#()"~a-~a"s(if(<=(* s 10)b)b(subseq d(or(mismatch d(#1#()"~a"s))(length d))))))

```

Try it online!

Smallest, Biggest.

Ungolfed:

```
(defun f(s b &aux (d (format () "~a" b)))   ; s and b parameters, d string from s
  (format () "~a-~a" s                     ; print first number, then -, then abbreviation
      (if (<= (* s 10) b)                  ; if b is too large do not abbreviate
          b
          (subseq d (or (mismatch d (format () "~a" s)) ; else find first mismatch
                        (length d))))))    ; then extract the last part from mismatch
                                           ; or nothing if they are equal

```
> 0 votes

---
Tags: code-golf, number
---


title: Big integer multiplication

text:
# Question
Title: Big integer multiplication
Your challenge (if you choose to accept it) is to implement big integer multiplication in the shortest code possible.

Rules:

* Take two integers (decimal form) as ASCII strings from the command line parameters of your program. If your language doesn't support command line parameters, I'll accept stdin or similar input mechanisms.
* Output should be in ASCII decimal form, via a standard output mechanism (e.g. stdout)
* Must support both positive and negative integers, as well as zero.
* Must support *any* length integer integers up to `2**63` characters long, or at least the maximum you can store in memory.
* You may not use any in-built classes or functionality that handles big integers.
* The largest data type you may use is a 64-bit unsigned integer.
* You may not use floating point operations.
* You do not have to implement checks for valid inputs.

Example:

```
> multiply.exe 1234567890 987654321
1219326311126352690

```

Enjoy :)

# Answer
## APL (~~124~~ ~~120~~ 116)

This is way too long. It does grade school multiplication.

```
N←{↓⌽↑⌽¨⍵}⋄S↓'-',A/⍨∨\×A←{∨/M←9<T←0,⍵:∇(1⌽M)+T-M×10⋄⍵}⊃+/N↑⍨⌿2L⍴E,(L-1)+⍳L←⊃⍴E←⌽Y∘×¨⊃X Y←N⍎¨¨A~¨'-'⊣S←1≠+/'-'∊¨A←⍞⍞

```

Explanation:

* `N←{↓⌽↑⌽¨⍵}`: `N` is a function that, given a vector of vectors, makes all the vectors the same length, padding with zeroes at the front. It does this by reversing all inner vectors (`⌽¨`), turning the vector of vectors into a matrix (), reversing this matrix (), and turning it back into a vector of vectors ().
* `S←1≠+/'-'∊¨A←⍞⍞`: Read two lines of input, as characters (`⍞⍞`), store them in A, and count how many minuses there are in the input. `S` is zero or one depending on whether the result will be positive.
* `X Y←N⍎¨¨A~¨'-'`: In A (our input) without (`~`) the minuses, evaluate each separate character (`⍎¨¨`), run it through the N function and save the two vectors in X and Y. If the input was `123` `32`, we now have `X=1 2 3 Y=0 3 2`.
* `L←⊃⍴E←⌽Y∘×¨⊃X Y`: For each digit in the first vector, produce a vector with the digits from the second vector multiplied by that digit. Reverse this vector of vectors so that the least significant one is at the front. Store this vector in E and its length in L.
* `+/N↑⍨⌿2L⍴E,(L-1)+⍳L`: Shift all of these vectors left, padding with zeroes on the right, by their index. Run them through N again so that they're all the same length. Then add all these vectors together. I.e.:

```
       1 2 3
         3 2
      ------
       2 4 6 (shift 0)
     3 6 9   (shift 1)
    --------
    3 8 13 6 (before carry)
     3 9 3 6 (after carry)

```
* `A←{∨/M←9<T←0,⍵:∇(1⌽M)+T-M×10⋄⍵}`: Carry the ones. As long as there are still 'digits' higher than 10 (`∨/M←9<T←0,⍵`), add one to the next significant digit (`∇(1⌽M)+T`) and remove 10 from the offending digit (`-M×10`).
* `'-',A/⍨∨\×A`: Remove any leading zeroes from the result vector, and add a minus in front.
* `S↓`: Remove `S` characters from the front, i.e. if the result is supposed to be positive then remove the minus again.
> 11 votes

# Answer
# Javascript, 147 chars

```
a=prompt(b=prompt(j=c=[]))
for(i=a.length;j--||(j=b.length,n=0,i--);)c[i+j]=(n=~~c[i+j]+n/10+~~b[j-1]*~~a[i]|0)%10
" -"[10>a[0]^10>b[0]]+c.join("")

```
> 4 votes

# Answer
### Scala 567 519

```
type I=List[Long]
type S=String
object C extends App{
def g(l:I,s:I=Nil,i:Long=0L):I=if(l.isEmpty)(i/10::i%10::s).dropWhile(_==0)else
g(l.tail,(l(0)+i)%10::s,(l(0)+i)/10)
def m(p:S,q:S)=g((p.reverse.zipWithIndex.map{a=>q.reverse.zipWithIndex.map(b=>((""+a._1).toLong*(""+ b._1).toLong,a._2+b._2))}.flatten.groupBy(_._2).map(m=>(m._1,m._2.map(_._1)sum))).toList.sortBy(_._1).map(_._2)).mkString
def f(s:S,t:S)=(if((s+t).matches("[^-]*-[^-]*"))"-"else"")+m(s.filter(_!='-'),t.filter(_!='-'))
println(f(args(0),args(1)))
}

```

### updated: Use some `Longs` for intermediate values, while in fact long `Ints` passed as `Strings` can't exceed the length of `Int.MaxValue`.

Far away from the APL-range, this compilable Scala code multiplies 2 ints of 100digits in about a second on a 7 y'o machine.

I have an ungolfed version which doesn't work :) . Method m seemed to work with a loop, but only because for some map sizes, the map was sorted in the way the g-Method expected the values.

Of course I can sort it, but then I got problems with leading/trailing zeros, or 1-digit values. I tried with `("12345").map` in the REPL, and it worked quickly, so I made a test how far I could golf the loop-version, and got nearly the same result - 143 chars here, 145 chars there, so I took my working solution.

So how does the code work: 3 methods:

* f) evaluate sign with regex, to append it in the end, and remove the - when calling b)
* m) zips both Strings with indexes, mupltiplies each digit with each and sums their indexes. Then groups by index sum, sorts by index sum, sums the values therein. Hands the List of values to c)
* g) takes the number, and keeps the last digit. Divides the rest and adds it to the head of the rest of the list, which gets proceeded the same way until empty.

From the REPL, multiplying 1234567890 987654321 The first column from below shows the result digit calculated, except the leading digit which is the overflow from the last computation, and is in column 2.

```
Replaying:
sum((p.reverse.zipWithIndex.map{a=>q.reverse.zipWithIndex.map(b=>((""+a._1).toInt*(""+ b._1).toInt,a._2+b._2))}.flatten.groupBy(_._2).map(m=>(m._1,m._2.map(_._1)sum))).toList.sortBy(_._1).map(_._2)).mkString.reverse
    0  : 0  ::  List(9, 26, 50, 80, 115, 154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    9  : 0  ::  List(26, 50, 80, 115, 154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    6  : 2  ::  List(50, 80, 115, 154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    2  : 5  ::  List(80, 115, 154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    5  : 8  ::  List(115, 154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    3  : 12  ::  List(154, 196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    6  : 16  ::  List(196, 240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    2  : 21  ::  List(240, 285, 240, 196, 154, 115, 80, 50, 26, 9)
    1  : 26  ::  List(285, 240, 196, 154, 115, 80, 50, 26, 9)
    1  : 31  ::  List(240, 196, 154, 115, 80, 50, 26, 9)
    1  : 27  ::  List(196, 154, 115, 80, 50, 26, 9)
    3  : 22  ::  List(154, 115, 80, 50, 26, 9)
    6  : 17  ::  List(115, 80, 50, 26, 9)
    2  : 13  ::  List(80, 50, 26, 9)
    3  : 9  ::  List(50, 26, 9)
    9  : 5  ::  List(26, 9)
    1  : 3  ::  List(9)
    2  : 1  ::  List()
    res45: String = 1219326311126352690

```

...321 * ...890 leads to

```
index   Product of
sum     Digits
0 =>             1*0 =>      0 => 0
1 =>       2*0 + 1*9 =>    0+9 => 9
2 => 3*0 + 2*9 + 1*8 => 0+18+8 =>26

```

### Ungolfed version:

```
object BigMul extends App {
   // i is the overrun from the previous value
  def oSum (l: List[Int], sofar: List[Int] = Nil, i: Int=0): List[Int] = {
    /*
    println (sofar + " <- " + (i/10) + "  : " + (({
        if (l.isEmpty) 0 else l.head} +i) %10) + "  ::  " + {
      if (l.isEmpty) "()" else l.tail} )
    */
    if (l.isEmpty) (i / 10 :: i%10 :: sofar).dropWhile (_==0)  else
    oSum (l.tail, (l.head + i) % 10 :: sofar, (l.head + i) / 10)
  }

  // works, but not really ungolfed:
  /* well, yes, this is mapple-di-map
  def mul (p:String,q:String)=
    osum ((p.reverse.zipWithIndex.map {a=>
          q.reverse.zipWithIndex.map (b=>
       (("" + a._1).toInt * ("" + b._1).toInt, a._2 + b._2))}.
       flatten.groupBy (_._2).map (m=>
         (m._1, m._2.map (_._1)sum))).
         toList.sortBy (_._1).map (_._2)).mkString
  */
  // buggy version, but nearly there:
  def mul (s: String, t: String) = {
    val li = for (i <- (s.size -1 to 0 by -1);
      j <- (t.size -1 to 0 by -1);
       a=("" + s(i)).toInt;
      b=("" + t(j)).toInt)
        yield (a*b, i + j)
    osum ((li groupBy (_._2)).toList.sortBy (_._1).
      map (_._2.map (_._1).sum)).
      init.mkString.reverse+"0"
  }

  def signedMul (s: String, t: String) = (s(0), t(0)) match {
    case ('-', '-') => mul (s.tail, t.tail)
    case ('-',   _) => "-"+ mul (s.tail, t)
    case (  _, '-') => "-"+ mul (s, t.tail)
    case (  _,   _) => mul (s, t)
  }

  println (signedMul (args (0), args (1)))
}

```
> 3 votes

# Answer
### C# ~~619~~ 585

```
using System.Linq;class P{static void Main(string[] a){var p=new P();string m=p.S(a[0]),n=p.S(a[1]);var l=m.Length+n.Length;var r=p.s+p.C(Enumerable.Range(0,l).Reverse().Select(j=>n.Reverse().Select((y,i)=>(p.C(m.Reverse().Select(z=>(y-48)*(z-48)).ToArray())+new string('0',i)).PadLeft(l,'0')).Select(s=>s[j]-48).Sum()).ToArray()).TrimStart('0');System.Console.WriteLine(r!=""?r:"0");}string C(int[]e){var i=0;var r="";foreach(var z in e.Select(z=>z+i)){i=z/10;r=z%10+r;}return i+r;}string s="";string S(string a){if(!a.StartsWith("-"))return a;s=s==""?"-":"";return a.Substring(1);}}

```

Test link: http://ideone.com/ghY9G0 (with a small modification: in ideone the input is taken from stdin, as I don't think it's possible to pass command line args).
> 2 votes

# Answer
## Python, 174 Chars (Positive Only)

```
import sys
a,b=sys.argv[1:]
l=len(a+b)
x=map(int,a[::-1]+'0'*l+b)
i=r=0
t=""
while i<l:r+=sum(x[i-j]*x[-1-j]for j in range(i+1));t=str(r%10)+t;r/=10;i+=1
print t.lstrip('0')

```
> 1 votes

# Answer
### GolfScript, 117 chars

```
-1%" "/~0{1$)\;45={)2%\);\}*}:l~@\l@@""\{15&2$0\{15&2$*+@.!{"\0"+}*(@+@\.10/\10%}%[\](\+@;\;\0\+\}/\;{`+}*\{"-"+}*-1%

```

Two numbers (optional '-'-sign is supported) separated by space must be given on STDIN. Unfortunately the result printed to STDOUT may have leading zeros.

It is a direct approach implemented in golfscript so it should still be possible to golf this program further.
> 1 votes

# Answer
## Python, 327

This is utterly terrible. Utterly utterly terrible. I could probably tighten it up (performance- and golf-wise) by implementing proper addition. Instead, I use successive addition & subtraction, brainfuck style. UTTERLY. TERRIBLE. But I guarantee I never blow the 64-bit limit, unlike some other solutions I'm not going to mention. (only... I already commented on them, and I think I just mentioned them)

```
import sys
a,b=sys.argv[1:]
s=a[0]<'0'
t=b[0]<'0'
a=a[s:][::-1]
b=b[t:][::-1]
a,b=(map(int,x)for x in(a,b))
def x(c,y,r):
 k=0
 while not-1<c[k]-y<10:c[k]=r;k+=1
 c[k]-=y
 if c[-1]<1:c.pop()
e=[]
a*=1-([0]in(a,b))
while a:
 x(a,1,9);d=b[:]
 while d:x(d,1,9);e+=[0];x(e,-1,0)
print'-'*(s^t)+''.join(map(str,e[::-1]+[0]*(e==[])))

```
> 1 votes

# Answer
# Haskell, 240 bytes

```
[d]!n=0#map(*d)n;(d:r)!n=0#(zipWith(+)([d]!n++cycle[0])$0:r!n);0#[]=[];z#[]=[z];z#(x:r)=mod(z+x)10:div(z+x)10#r;r=reverse;l=r.map(read.pure).show.abs;a?b|(a<0)/=(b<0)='-'|0<1=' ';main=do[a,b]<-map read<$>getArgs;putStr$a?b:r(l a!l b>>=show)

```

Try it online!

Could probably be quite a bit shorter but for the rather inconvenient IO format. Implements the "elementary school" multiplication algorithm, storing and processing numbers as lists of ints, representing each digit of a number.
> 1 votes

---
Tags: code-golf, math
---


title: Exploded Suffixes

text:
# Question
Title: Exploded Suffixes
Given an ASCII string, output the exploded suffixes of it. For example, if the string was `abcde`, there are 5 suffixes, ordered longest to shortest:

```
abcde
bcde
cde
de
e

```

Each suffix is then *exploded*, meaning each character is copied as many times as its one-indexed location in that suffix. For example, exploding the suffixes of `abcde`,

```
abcde
12345
abbcccddddeeeee

bcde
1234
bccdddeeee

cde
123
cddeee

de
12
dee

e
1
e

```

Altogether, the exploded suffixes of `abcde` are

```
abbcccddddeeeee
bccdddeeee
cddeee
dee
e

```

## Rules

* This is so the shortest code wins.
* The input will consist of the printable ASCII characters. (This excludes newlines but includes spaces.)
* The output will have each string on a separate line.
* Trailing spaces are allowed on each line and there may be an extra newline at the end.

## Test Cases

```
''

'a'
a

'bc'
bcc
c

'xyz'
xyyzzz
yzz
z

'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f

's p a c e'
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e

```

# Answer
> 14 votes
# Jelly, 5 bytes

```
ṫJxJY

```

Try it online! or verify all test cases.

### How it works

```
ṫJxJY  Main link. Argument: s (string)

 J     Indices; yield I := [1, ..., len(s)].
ṫ      Tail; get the suffixes of s starting at indices [1, ..., len(s)].
   J   Indices; yield I again.
  x    Repeat. The atom 'x' vectorizes at depth 1 (1D arrays of numbers/characters)
       in its arguments. This way, each suffix t gets repeated I times, meaning
       that the first character of t is repeated once, the second twice, etc.
       If left and right argument have different lengths, the longer one is
       truncated, so I can safely be applied to all suffixes.
    Y  Join, separating by linefeeds.

```

# Answer
> 8 votes
# J, ~~22~~ ~~12~~ 8 bytes

*Thanks to miles for saving 14 bytes!*

```
(#~#\)\.

```

Now this is a really nice solution. Pretty succinct, too.

This is the hook `#~#\` applied to the suffixes (`\.`) of the input. The hook, when called on input `y`, is decomposed as thus:

```
(#~#\) y
y #~ #\ y

```

Here are some intermediate results:

```
   ]s =: 's p a c e'
s p a c e
   #\ s
1 2 3 4 5 6 7 8 9
   (quote) s
's p a c e'
   (quote;#)\ s
+-----------+-+
|'s'        |1|
+-----------+-+
|'s '       |2|
+-----------+-+
|'s p'      |3|
+-----------+-+
|'s p '     |4|
+-----------+-+
|'s p a'    |5|
+-----------+-+
|'s p a '   |6|
+-----------+-+
|'s p a c'  |7|
+-----------+-+
|'s p a c ' |8|
+-----------+-+
|'s p a c e'|9|
+-----------+-+
   1 2 3 # '123'
122333
   3 3 3 # '123'
111222333
   ]\. s
s p a c e
 p a c e
p a c e
 a c e
a c e
 c e
c e
 e
e
   quote\. s
's p a c e'
' p a c e'
'p a c e'
' a c e'
'a c e'
' c e'
'c e'
' e'
'e'
   (#~#\) s
s  ppp    aaaaa      ccccccc        eeeeeeeee
   (#~#\)\. s
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e

```

## Test cases

```
   f =: (#~#\)\.
   f
(#~ #\)\.
   f ''
   f 'a'
a
   f 'bc'
bcc
c
   f 'xyz'
xyyzzz
yzz
z
   f 'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f
   f 's p a c e'
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e

   ]tc =: <;._1 '|' , '|a|bc|xyz|code-golf|s p a c e'
++-+--+---+---------+---------+
||a|bc|xyz|code-golf|s p a c e|
++-+--+---+---------+---------+
   ,. f &. > tc
+---------------------------------------------+
+---------------------------------------------+
|a                                            |
+---------------------------------------------+
|bcc                                          |
|c                                            |
+---------------------------------------------+
|xyyzzz                                       |
|yzz                                          |
|z                                            |
+---------------------------------------------+
|coodddeeee-----ggggggooooooollllllllfffffffff|
|oddeee----gggggoooooolllllllffffffff         |
|dee---ggggooooollllllfffffff                 |
|e--gggoooolllllffffff                        |
|-ggooollllfffff                              |
|goolllffff                                   |
|ollfff                                       |
|lff                                          |
|f                                            |
+---------------------------------------------+
|s  ppp    aaaaa      ccccccc        eeeeeeeee|
| pp   aaaa     cccccc       eeeeeeee         |
|p  aaa    ccccc      eeeeeee                 |
| aa   cccc     eeeeee                        |
|a  ccc    eeeee                              |
| cc   eeee                                   |
|c  eee                                       |
| ee                                          |
|e                                            |
+---------------------------------------------+

```

# Answer
> 7 votes
## Python, 61 bytes

```
f=lambda s,i=0:s[i:]and-~i*s[i]+f(s,i+1)or s and'\n'+f(s[1:])

```

Alternative 63:

```
f=lambda s,b=1:s and f(s[:-1],0)+s[-1]*len(s)+b*('\n'+f(s[1:]))

```

# Answer
> 6 votes
# Python 3, ~~91~~ ~~68~~ 65 bytes

```
def f(s):f(s[1:print(''.join(i*c for i,c in enumerate(s[0]+s)))])

```

Terminates with an error after printing the desired output. Test it on Ideone.

### How it works

Before **f** can call itself recursively, the indices of `s[1:...]` have to be computed.

First `enumerate(s[0]+s)` yields all pairs **(i, c)** of characters **c** of **s** – with its first character duplicated – and the corresponding indices **i**. Prepending `s[0]` serves two purposes here.

* The first character of **s** has to be repeated once, but the first index is **0**.
* Once all characters have been processed, `s[0]` will raise an *IndexError*, causing **f** to terminate with an error rather than printing newlines until the recursion limit is reached.

`''.join(i*c for i,c in ...)` builds a flat string of each **c** repeated **i** times, which `print` echoes to STDOUT.

Finally, since `print` returns *None* and `s[1:None]` is simply `s[1:]`, the recursive call `f(s[1:...])` repeats the above process for **s** without its first character.

# Answer
> 6 votes
# Perl 6, 38 bytes

```
m:ex/.+$/.map:{put [~] .comb Zx 1..*}

```

37 bytes + 1 for `-n` command line switch

## Example:

```
$ perl6 -ne 'm:ex/.+$/.map:{put [~] .comb Zx 1..*}' <<< 'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f

```

## Expanded:

```
# -n command line switch takes each input line and places it in ｢$_｣

# You can think of it as surrounding the whole program with a for loop
# like this:
for lines() {

  # match
  m
  :exhaustive # every possible way
  / .+ $/     # at least one character, followed by the end of the string

  .map:

  {
    put           # print with newline
      [~]         # reduce using string concatenation ( don't add spaces between elements )
        .comb     # split into individual chars
        Z[x]      # zip using string repetition operator
        1 .. *    # 1,2,3,4 ... Inf
  }

}

```

# Answer
> 6 votes
# Brachylog, 17 bytes

```
@]Elyk:Erz:jac@w\

```

Try it online!

### Explanation

```
@]E                 E is a suffix of the Input
   lyk              The list [0, ..., length(E) - 1]
      :Erz          The list [[0th char of E, 0], ..., [Last char of E, length(E) - 1]]
          :ja       For all elements of that list, concatenate the Ith char I times to itself
             c      Concatenate the list into a string
              @w    Write followed by a line break
                \   False: backtrack to another suffix of the Input

```

# Answer
> 4 votes
# Haskell, 48 bytes

```
e=map(concat.zipWith replicate[1..]).scanr(:)[]

```

is interfaced by any of

```
ghc exploded_suffixes.hs -e 'e"abcde"'
ghc exploded_suffixes.hs -e 'mapM_ putStrLn.e=<<getLine' <<<code-golf
ghc exploded_suffixes.hs -e 'Control.Monad.forever$putStr.unlines.e=<<getLine'

```

# Answer
> 4 votes
# C#, 101 bytes

```
f=s=>{var r="\n";for(int i=0;i<s.Length;)r+=new string(s[i],++i);return""==s?r:r+f(s.Substring(1));};

```

Recursive anonymous function, which also prints a leading newline. If the leading newline is not allowed, 3 extra bytes turn it into a trailing newline:

```
f=s=>{var r="";for(int i=0;i<s.Length;)r+=new string(s[i],++i);return""==s?r:r+"\n"+f(s.Substring(1));};

```

Full program with ungolfed method and test cases:

```
using System;

namespace ExplodedSuffixes
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f = null;
            f = s =>
            {
                var r = "\n";
                for (int i = 0; i < s.Length; )
                    r += new string(s[i], ++i);
                return "" == s ? r : r + f(s.Substring(1));
            };

            // test cases:
            string x = "abcde";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "a";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "bc";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "xyz";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "code-golf";
            Console.WriteLine("\'" + x + "\'" + f(x));
            x = "s p a c e";
            Console.WriteLine("\'" + x + "\'" + f(x));
        }
    }
}

```

# Answer
> 4 votes
# 05AB1E, 13 bytes

```
.sRvyvyN>×}J,

```

Try it online!

**Explanation**

```
.s              # push list of suffixes of input
  R             # reverse the list
   vy           # for each string
     vy   }     # for each char in string
       N>×      # repeat it index+1 times
           J,   # join and print with newline

```

# Answer
> 4 votes
## CJam, 14 bytes

```
Sl+{_eee~n1>}h

```

Try it online!

### Explanation

```
Sl+   e# Read input and prepend a space.
{     e# While the string is non-empty...
  _   e#   Make a copy.
  ee  e#   Enumerate. Gives, e.g. [[0 ' ] [1 'a] [2 'b] [3 'c]].
  e~  e#   Run-length decode. Gives "abbccc".
  n   e#   Print with trailing linefeed.
  1>  e#   Discard first character.
}h

```

# Answer
> 3 votes
# Java, ~~150~~ 127 bytes

Edit:

* ***-23** bytes off. Thanks to @Kevin Cruijssen*

Snipet:

```
f->{String s[]=f.split(""),o="";int i=-1,j,l=s.length;for(;++i<l;)for(j=-2;++j<i;o+=s[i]);return l<1?"":o+"\n"+f.substring(1);}

```

Ungolfed:

```
public static String explodeSuff(String suff){
  char [] s = suff.toCharArray();
  String out = "";
  if(s.length==0)return "";
  for(int i=-1;++i<s.length;){
    for(int j=-2;++j<i;){
      out+=s[i];
    }
  }
  return out+"\n"+suff.subString(1);
}

```

# Answer
> 3 votes
## Perl, 36 + 1 (`-n`) = 37 bytes

```
/.+$(?{$.=say$&=~s%.%$&x$.++%rge})^/

```

Needs `-n` and `-E` (or `-M5.010`) to run :

```
perl -nE '/.+$(?{$.=say$&=~s%.%$&x$.++%rge})^/' <<< "code-golf"

```

Note that it works on only one instance each time you run it (because it uses the variable `$.` which is incremented every time a line is read, so it hold `1` only the first time a line is read). (But no problem here, just `^D` and re-run it!)

# Answer
> 3 votes
# Retina, 31 bytes

Byte count assumes ISO 8859-1 encoding.

```
M&!`.+

$.%`$*»
%+r`»($|.)
$1$1

```

Try it online!

# Answer
> 2 votes
## Racket 184 bytes

```
(let p((l(string->list s))(ol'()))(cond[(null? l)(display(list->string(flatten ol)))]
[else(p(cdr l)(append ol(list #\newline)(for/list((i l)(n(length l)))(for/list((j(+ 1 n)))i))))]))

```

Ungolfed:

```
(define(f s)
 (let loop((l(string->list s))
             (outl '()))
    (cond
      [(null? l)
       (display
        (list->string
         (flatten outl)))]
      [else
       (loop
        (rest l)
        (append outl
                (list #\newline)
                (for/list ((i l)
                           (n (length l)))
                  (for/list ((j (add1 n)))
                    i
                    ))))]  )))

(f "abcde")
(f "xyz")

```

Output:

```
abbcccddddeeeee
bccdddeeee
cddeee
dee
e

xyyzzz
yzz
z

```

# Answer
> 2 votes
## JavaScript (ES6), 65 bytes

```
f=s=>s?[s.replace(/./g,(c,i)=>c.repeat(i+1)),...f(s.slice(1))]:[]
```

```
<input oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```

Previous attempts:

```
67: s=>[...s].map((_,i)=>s.slice(i).replace(/./g,(c,i)=>c.repeat(i+1)))
84: s=>s.replace(/./g,`$&$'
    `).match(/.+/g).map(s=>s.replace(/./g,(c,i)=>c.repeat(i+1)))
89: f=(s,t=s.replace(/./g,(c,i)=>c.repeat(i+1)))=>t?[]:[t,...f(s,t.replace(/(.)(?=\1)/g,''))]

```

# Answer
> 2 votes
# MATL, 12 bytes

```
&+gYRYs"G@Y"

```

*I love it when quote marks come together!*

Try it online!

### Explanation

This works by building a matrix whose columns are used, one by one, to run-length decode the input. As an example, for input `'abcde'` the matrix is

```
1 0 0 0 0
2 1 0 0 0
3 2 1 0 0
4 3 2 1 0
5 4 3 2 1

```

Code:

```
&+g    % Implicit input. NxN matrix of ones, where N is input size
YR     % Set entries above diagonal to zero
Ys     % Cumulative sum of each column. This gives the desired matrix
"      % For each column
  G    %   Push input (for example 'abcde')
  @    %   Push current column (for example [0;0;1;2;3])
  Y"   %   Run-length decode (example output 'cddeee')
       % Implicit end
       % Implicit display

```

# Answer
> 2 votes
# PHP, 103 bytes (99 with short tags)

```
<?php for($s=$argv[1];""!=$s[$i++];$o.="
")for($j=0;""!=$l=$s[$j+$i-1];)$o.=str_pad('',++$j,$l);echo$o;

```

I'm pretty certain this isn't the shortest possible answer.

# Answer
> 1 votes
# Python 3, 95 bytes

```
def f(s):return'\n'.join(''.join(s[j:][i]*(i+1)for i in range(len(s)-j))for j in range(len(s)))

```

This was surprisingly harder than I expected it to be. I redid my whole function maybe 4 times.

# Answer
> 1 votes
# Java 7,140 bytes

```
void c(char[]a,int l,int j){if(l<1)return;c(a,--l,++j);for(int i=0,k;i<j;i++)for(k=0;k++<=i;)System.out.print(a[i+l]);System.out.println();}

```

# Ungolfed

```
 void c(char[]a,int l,int j)
{
if (l < 1)
return ;
c(a , --l , ++j) ;
for(int i = 0 , k; i < j ; i++)
for(k = 0 ; k++ <= i ;)
System.out.print(a[i+l]);
System.out.println();
}

```

Following line giving me very pain.i don't know how can i golfed it(because there are two loops to break the condition to put `"\n"` in print statement).
`System.out.println();`

# Answer
> 1 votes
## Pyke, 12 bytes

```
VilS],A*s
}t

```

Try it here!

# Answer
> 1 votes
# Ruby, 51 bytes

Uses the `-n` flag for +1 byte.

```
(k=0;puts$_.gsub(/./){$&*k+=1};$_[0]="")while$_>$/

```

# Answer
> 1 votes
# R, 108 bytes

Read input from stdin and prints to stdout

```
s=scan(,"");n=nchar(s);for(i in 1:n)cat(do.call("rep",list(strsplit(s,"")[[1]][i:n],1:(n-i+1))),"\n",sep="")

```

I felt the use of `do.call` was appropriate here. It basically takes two inputs: 1. a function name in form of a string (`rep` here) and a list of arguments and 2. iteratively applies calls the function using the arguments in the list.

E.g.:

* `rep("c",3)` produces the vector `"c" "c" "c"`
* `do.call("rep",list(c("a","b","c"),1:3))` produces the vector `"a" "b" "b" "c" "c" "c"`
* which is equivalent to consecutively calling `rep("a",1)`, `rep("b",2)` and `rep("c",3)`

# Answer
> 1 votes
# Vim, 43 bytes

`qqYlpx@qq@qqr0<C-H><C-V>{$:s/\v%V(.)\1*/&\1/g<CR>@rq@r`

First macro separates the suffixes, second macro "explodes" them. Likely beatable. Spaces are annoying.

# Answer
> 1 votes
# C, 186 Bytes

```
#include <string.h>
#define S strlen
p(char* s){char *t=s;char u[999]="";for(int i=0;i<S(s);i++){for(int j=i+1;j>0;j--){sprintf(u+S(u),"%c",*t);}t++;}printf("%s\n",u);if(S(s)>1)p(s+1);}

```

This probably can be shortened quite a bit, but I just wanted to try it. It's my second try at golf, so give me any pointers (\*lol) you can. It takes a string as a parameter and does the exploding from there. u is used as a buffer that stores the exploded string.

Ungolfed:

```
#include <string.h>
#define S strlen
p(char* s){
    char *t=s;
    char u[999]="";
    for(int i=0;i<S(s);i++){
        for(int j=i+1;j>0;j--){
            sprintf(u+S(u),"%c",*t);
        }
        t++;
    }
    printf("%s\n",u);
    if(S(s)>1)p(s+1);
}

```

# Answer
> 1 votes
## *Acc!!*, 150 bytes

Expects input on stdin, terminated with a tab character.

```
N
Count c while _/128^c-9 {
_+N*128^(c+1)
}
Count i while _-9 {
Count j while _/128^j-9 {
Count k while j+1-k {
Write _/128^j%128
}
}
Write 10
_/128
}

```

### Explanation

This is actually a pretty good task for *Acc!!*, since it only requires reading a string and iterating over it with some nested loops. We read the string into the accumulator, treating it as a sequence of base-128 digits, with the first character on the low-order end. After the opening `Count c` loop, the accumulator value can be conceptualized like this (using `xyz` as example input):

```
128^   3  2  1  0
     tab  z  y  x

```

(The actual accumulator value for this example is `9*128^3 + 122*128^2 + 121*128 + 120` = `20888824`.)

We can then iterate over the string by iterating over increasing powers of 128. And we can iterate over the suffixes by dividing the accumulator by 128 after each iteration, chopping off a character.

With indentation and comments:

```
# Initialize the accumulator with the first input character
N
# Loop until most recent input was a tab (ASCII 9)
Count c while _/128^c - 9 {
    # Input another character and add it at the left end (next higher power of 128)
    _ + N * 128^(c+1)
}

# Loop over each suffix, until only the tab is left
Count i while _ - 9 {
    # Loop over powers of 128 until the tab
    Count j while _/128^j - 9 {
        # Loop (j+1) times
        Count k while j + 1 - k {
            # Output the j'th character
            Write _ / 128^j % 128
        }
    }
    # Output a newline
    Write 10
    # Remove a character
    _/128
}

```

# Answer
> 1 votes
# Vyxal `j`, 6 bytes

```
ÞKvÞżṠ

```

Try it Online!

# Answer
> 0 votes
# Knight, 48 bytes

```
;=xP Wx;=iF;W<=i+1i+1LxO+*Gx-iT1i"\";O""=xSxF1""

```

Try it online!

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


title: Print the nth prime that contains n

text:
# Question
Title: Print the nth prime that contains n
This question will be a twist on finding the `n`th prime number.

# Challenge

You must write a program that will take one input `n`, and output the `n`th prime number whose decimal representation contains the decimal representation of `n` as a subtring.

Confused? Here are some examples.

```
n=1
Primes: 2, 3, 5, 7, 11
                    ^1 first prime that contains a 1
Output: 11

n=2
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
        ^1                          ^2 second prime that contains a 2
Output: 23

n=3
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
           ^1           ^2          ^3 third prime that contains a 3
Output: 23

n=10
Primes: 2, 3, 5, 7, 11, ..., 97, 101, 103, 107, 109, ..., 997, 1009, 1013, 1019, 1021, 1031, 1033
                                 ^1   ^2   ^3   ^4             ^5    ^6    ^7    ^8    ^9    ^10 tenth prime that contains a 10
Output: 1033

```

---

This is , so lowest byte count wins.

If something is confusing, please leave a comment.

# Answer
> 12 votes
# 05AB1E, 8 bytes

Code:

```
µN¹åNp*½

```

Explanation:

```
µ          # Run this until the counting variable has reached the input value.
 N¹å       # Check if the input number is in the range variable.
    Np     # Check if the range variable is prime.
      *    # Multiply those two numbers (which is basically an AND operator).
       ½   # If true, increment the counting variable.
           # After the loop, the stack is empty and implicitly prints N.

```

Uses **CP-1252** encoding. Try it online!.

# Answer
> 10 votes
# Pyth - 11 bytes

```
e.f&P_Z}`Q`

```

Test Suite.

# Answer
> 9 votes
# Python 2, ~~67~~ ~~65~~ 62 bytes

```
f=lambda n,k=0,m=2,p=1:k/n or-~f(n,k+p%m*(`n`in`m`),m+1,p*m*m)

```

Test it on Ideone.

### How it works

We use a corollary of Wilson's theorem:

At all times, the variable **p** is equal to the square of the factorial of **m - 1**.

If **k \< n**, `k/n` will yield **0** and **f** is called recursively. **m** is incremented, **p** is updated, and **k** is incremented if and only if **m** is a prime that contains **n**.

The latter is achieved by adding the result of `p%m*(`n`in`m`)` to **k**. By the corollary of Wilson's theorem if **m** is prime, `p%m` returns **1**, and if not, it returns **0**.

Once **k** reaches **n**, we found **q**, the **n**th prime that contains **n**.

We're in the next call during the check, so **m = q + 1**. `k/n` will return **1**, and the bitwise operators `-~` will increment that number once for every function call. Since it takes **q - 1** calls to **f** to increment **m** from **2** to **q + 1**, the outmost call to **f** will return **1 + q - 1 = q**, as intended.

# Answer
> 7 votes
## Bash, 27 bytes

```
primes 0|grep $1|sed $1q\;d

```

`primes` comes from bsdgames.

Takes input as a command line argument, and outputs on STDOUT.

# Answer
> 5 votes
# Jelly, 13 bytes

```
×ÆP,³Dœṣ/Ṗµ#Ṫ

```

Try it online!

# Answer
> 4 votes
# Mathematica, 75 bytes

```
Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&

```

May still be golfable.

# Answer
> 4 votes
# Java, 194 180 173 ~~171~~ 112 Bytes

Code:

```
a->{int i=1,j,n,r=0;for(j=n=new Integer(a);(r+=++i>=j&(""+j).contains(""+n)?1:0)!=n;j+=j%i==0?i=1:0);return j;}

```

Ungolfed:

```
class P{
    static int i=1,j,n,r;
    public static void main(String[]s) {
        for(
                j=n=new Integer(s[0]); //executes once before first iteration
                (r+=++i>=j&(""+j).contains(""+n)?1:0)!=n; //executes on first and every iteration
                j+=j%i==0?i=1:0 //executes after first and every iteration
           ) {
            ;
        }
        System.out.print(j);
    }
}

```

# Answer
> 3 votes
# MATL, 18 bytes

```
`@YqVGVXf?3M]NG<]&

```

**Try it online!**

### Explanation

This generates primes in order using a `do...while` loop. For each prime, the condition is tested (and the prime is consumed). If satisfied, that prime is pushed to the stack again. The number of elements in the stack is used as count of how many qualifying primes we have found. When there are enough of them, the last one is displayed.

```
`         % Do...while
  @       %   Push iteration index, k. Starts at 1
  YqV     %   k-th prime. Convert to string
  GV      %   Push input, n. Convert to string
  Xf      %   Find string within another
  ?       %   If non-empty
    3M    %     Push k-th prime again (increase stack size by 1)
  ]       %   End if
  NG<     %   Is stack size less than input number? If so proceeed with
          %   a new iteration; else exit do...while loop
]         % End do...while
&         % Implicitly display only top number in the stack

```

# Answer
> 3 votes
## Ruby, ~~62~~ 61 bytes

```
->i{Prime.lazy.map(&:to_s).grep(/#{i}/).first(i)[-1]}

```

Requires the `-rprime` flag (+8 bytes).

```
->i{            # lambda with one argument
Prime           # iterator over all primes
.lazy           # make the iterator lazy (can't evaluate infinite primes)
.map(&:x.to_s)  # convert the primes to strings
.grep(/#{i}/)   # find primes that regex match on the input (contain it)
.first(i)       # take the first (input) primes that satisfy this
[-1]            # take the last of those
}

```

# Answer
> 3 votes
# Julia, ~~61~~ 60 bytes

```
f(n,k=0,m=1)=k<n&&f(n,k+isprime(m)contains("$m","$n"),m+1)+1

```

Try it online!

# Answer
> 2 votes
## Pyke, 15 bytes

```
Q.fD_P.I`Q`R{(e

```

Try it here!

# Answer
> 1 votes
# Bash + GNU coreutils, 66 Bytes

In contrast to @Doorknob's solution, this one only needs things that are installed on every GNU/Linux:

```
for((n=2;;n++)){
[ `factor $n|wc -w` -eq 2 ]&&grep $1<<<$n&&exit
}

```

# Answer
> 1 votes
# Java 8, ~~192~~ ~~183~~ ~~181~~ 171 bytes (full program)

```
interface M{static void main(String[]a){long n=new Long(a[0]),c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(a[0])?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);System.out.print(r);}}

```

Try it online.

**Explanation:**

```
interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    long n=new Long(a[0]),      //   Input argument as number
         c=0,                   //   Counter, starting at 0
         r=1,                   //   Result-number, starting at 1
         m,i;                   //   Temp number
    for(;c<n;                   //   Loop as long as `c` does not equals `n`
        c+=                     //     After every iteration: increase `c` by:
           m>1                  //      If the current `r` is a prime,
           &(r+"").contains(a[0])?
                                //      and this prime contains the input `n`
            1                   //       Increase `c` by 1
           :                    //      Else:
            0)                  //       Leave `c` the same
      for(m=++r,                //    Increase `r` by 1 first with `++r`, and set `m` to it
          i=2;i<m;              //    Inner loop `i` in the range [2, `m`)
        m=m%i++<1?              //     If `m` is divisible by `i`
           0                    //      Change `m` to 0 (so it's not a prime)
          :                     //     Else:
           m);                  //      Leave `m` unchanged
    System.out.print(r);}}      //    Print `r` as result

```

---

# Java 8, 105 bytes (lambda function)

```
n->{int c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(n+"")?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);return r;}

```

Try it online.

Same as above, but with `n` as integer input and without the verbose class stuff.

# Answer
> 1 votes
# Perl 6, 41 bytes

```
->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}

```

### Explanation:

```
-> $n { # has one parameter
  grep(
    {
      .is-prime # check that it is prime
      &&        # and
      / $n /    # that it contains the argument in the "string"
    },
    2 .. *      # for all numbers starting with 2
  )[ $n - 1 ]   # only take the $n-th one
                # ( accounting for 0 based array access )
}

```

### Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &prefix:<ℙ> = ->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}

my @test = (
  1  => 11,
  2  => 23,
  3  => 23,
  10 => 1033,
);

plan +@test;

for @test {
  is ℙ.key, .value, .gist
}

```

```
1..4
ok 1 - 1 => 11
ok 2 - 2 => 23
ok 3 - 3 => 23
ok 4 - 10 => 1033

```

# Answer
> 1 votes
# Japt `-h`, ~~15~~ ~~13~~ 11 bytes

```
_j ©ZsèU}jU

```

Try it

# Answer
> 1 votes
# Husk, 10 bytes

```
!fo`€d¹dİp

```

Try it online!

## Explanation

```
!fo`€d¹dİp
 fo     İp filter the infinite list of primes by the following:
     d¹    are the digits of n
   `€      a sublist of('`' switches the arguments)
       d   the digits of the number?
!          get nth element

```

# Answer
> 1 votes
# Stax, ~~14~~ 13 bytes

```
éâ^^εîï5~8<IM

```

Run and debug it

A good question for a generator.

-1 byte from recursive.

## Explanation

```
Z{|p_$yI^*}{gnH input: single number, n
             n  generator mode: count(stops after n values are found)
Z               push a 0 under the input(start value)
 {        }     filter block:
  |p            number is prime?
         *      and
    _$          string representation of number
      yI^       contains n?
           {g   generator block:
                implicit increment to get next number
              H get last generated value

```

# Answer
> 1 votes
# Haskell, 97 bytes

```
import Data.List
p n=[z|z<-[2..],all((>0).mod z)[2..z-1],show n`elem`subsequences(show z)]!!(n-1)

```

Try it online!

"subsequences" is an annoyingly long word. Thanks to @xnor for saving a byte.

# Answer
> 1 votes
# Vyxal, 8 bytes

```
‹Þp'?c;i

```

Try it Online!

# Answer
> 0 votes
## Clojure, 118 bytes

```
(defn s[n](nth(filter(fn[x](if(.contains(str x)(str n))(not-any? #(=(mod x %)0)(range 2 x))))(drop 2(range)))(dec n)))

```

Just gets the nth element of lazy infinite sequence of numbers which are prime and have `n` in their string representation.

You can try it here : https://ideone.com/ioBJjt

# Answer
> 0 votes
## PowerShell v2+, ~~108~~ 99 bytes

Ooof. The lack of any sort of built-in prime calculation/checking really hurts here.

```
param($n)for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){if("$i"-like"*$n*"){if(++$o-eq$n){$i;exit}}}}

```

Takes input `$n`, enters an infinite `for()` loop. Each iteration, we use a `for` loop wrapped around the PowerShell regex prime checker (h/t to Martin) to turn it into a prime generator by incrementing `$i` each time through the loop. (For example, running just `for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$i}}` will output `2, 3, 5, 7...` separated by newlines).

Then a simple `-like` check to see if `$n` is somewhere in `$i`, and increment our counter `$o`. If we've reached where `$n` and `$o` are equal, output `$i` and `exit`. Otherwise we continue through the `for` to find the next prime and the process repeats.

# Answer
> 0 votes
## Actually, 16 bytes

```
;$╗`P$╜@íu`╓dP.X

```

Try it online!

Explanation:

```
;$╗`P$╜@íu`╓dP.X
;$╗               make a copy of n, push str(n) to reg0
   `      `╓      push the first n values where f(k) is truthy, starting with k=0:
    P$              kth prime, stringified
      ╜@íu          1-based index of n, 0 if not found
            d     remove last element of list and push it to the stack (dequeue)
             P    nth prime
              .   print
               X  discard rest of list

```

# Answer
> 0 votes
# APL(NARS), 39 chars, 78 bytes

```
{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}

```

1π is the next prime number...; test:

```
  f←{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}
  f¨1 2 3 10
11 23 23 1033

```

but that already at 20 goes out the stack space... Instead this below seems ok even if has lenght a little more long (61 chars)

```
∇r←f w;i;k;s
r←2⋄s←⍕w⋄i←1
→0×⍳(w≤i)∧k←∨/s⍷⍕r⋄r←1πr⋄i+←k⋄→2
∇

  f¨1 2 3 10 20 100
11 23 23 1033 4201 100999

```

# Answer
> 0 votes
# Add++, 36 bytes

```
L,5*2^RßÞPABDBJVB]dG€Ωezß£*BZB]A1_$:

```

Try it online!

Fairly inefficient. Iterates over each integer \\$i\\$ such that \\$i \le 25x^2\\$ and filters out composites and primes that don't contain \\$n\\$. Finally, we take the \\$n\\$th value of the remaining integers.

---
Tags: code-golf, string, math, number, primes
---