title: Make a "Ceeeeeeee" program

text:
# Question
Title: Make a "Ceeeeeeee" program
Once I wrote a JavaScript program that would take as input a string and a character and would remove all characters except for the first one and the character given as input, one by one.

For example, computing this with inputs `codegolf.stackexchange.com` and `e` for the character yields:

```
codegolf.stackexchange.com
cdegolf.stackexchange.com
cegolf.stackexchange.com
ceolf.stackexchange.com
celf.stackexchange.com
cef.stackexchange.com
ce.stackexchange.com
cestackexchange.com
cetackexchange.com
ceackexchange.com
ceckexchange.com
cekexchange.com
ceexchange.com
ceechange.com
ceehange.com
ceeange.com
ceenge.com
ceege.com
ceee.com
ceeecom
ceeeom
ceeem
ceee

```

It keeps the first character and all `e`s. All other characters are removed one by one.

Your task is to write a program (or function) that takes two inputs and outputs (or returns) a string that accomplishes this effect.

## Specifications

* You can assume that the string will not contain any newlines.
* The second input will always be one character.
* If the answer is in the form of a function, you may return an array of strings containing each line in the output.
* The output can contain a trailing newline.

## Test Cases

`Test Cases`, `s`:

```
Test Cases
Tst Cases
Ts Cases
TsCases
Tsases
Tsses
Tsss

```

`Make a "Ceeeeeeee" program`, `e`:

```
Make a "Ceeeeeeee" program
Mke a "Ceeeeeeee" program
Me a "Ceeeeeeee" program
Mea "Ceeeeeeee" program
Me "Ceeeeeeee" program
Me"Ceeeeeeee" program
MeCeeeeeeee" program
Meeeeeeeee" program
Meeeeeeeee program
Meeeeeeeeeprogram
Meeeeeeeeerogram
Meeeeeeeeeogram
Meeeeeeeeegram
Meeeeeeeeeram
Meeeeeeeeeam
Meeeeeeeeem
Meeeeeeeee

```

`Hello World!`, `!`:

```
Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!

```

`Hello World!`, `z`:

```
Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!
H

```

`alphabet`, `a`:

```
alphabet
aphabet
ahabet
aabet
aaet
aat
aa

```

`upperCASE`, `e`:

```
upperCASE
uperCASE
uerCASE
ueCASE
ueASE
ueSE
ueE
ue

```

This is , so the shortest code (in bytes) wins.

# Answer
> 5 votes
# , 12 bytes

```
òYpó.“„a]òd

```

Try it online!

Hexdump:

```
00000000: f259 70f3 2e93 8412 615d f264            .Yp.....a].d

```

I have tested this with the latest version of V available before the challenge, and everything runs correctly, making this answer competing.

Explanation:

```
ò         ò    " Recursively:
 Yp            "   Duplicate this line
   ó           "   Remove:
    .a]      "     A compressed regex
            d  " Delete our extra line

```

The compressed regex translates to

```
.\zs[^e]

```

Which means

```
.           " Any character
 \zs        " Leave the previous character out of the selection
    [^e]    " Any character except for 'e' (Or whatever is given for input)

```

**11 bytes version**

This version uses a shortcut for `Yp` that wasn't available when this challenge was posted.

# Answer
> 31 votes
# Vim, ~~27, 26~~, 25 bytes

```
DJqqYp:s/.\zs[^<C-r>-]<CR>@qq@qD

```

Try it online!

Input comes in this format:

```
e
codegolf.stackexchange.com

```

My naive first approach is three bytes longer:

```
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd

```

I'm also happy with this answer because it starts with my name.

```
DJqq:t$|s/.\zs[^<C-r>"]<CR>@qq@qD
DJMcMayhem

```

See the similarity? Eh?

Less successful approaches:

```
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd
i:s/.\zs[^<Right>]<CR>@q<Esc>"adkqqYp@aq@qdd
DJ:s/.\zs[^<C-r>"]<CR>uqqYp@:@qq@qdd
DJqq:t.|$s/.\zs[^<C-r>"]<CR>@qq@qdd

```

Explanation:

```
D                                   " Delete everything on this first line
 J                                  " Remove this empty line
  qq                                " Start recording into register 'q'
    Y                               " Yank this line
     p                              " And paste it
      :s/                           " Run a substitute command on the last line in the buffer. Remove:
         .                          "   Any character
          \zs                       "   Move the selection forward (so we don't delete the first one)
             [^<C-r>-]              "   Followed by anything *except* for the character we deleted
                      <CR>          " Run the command
                          @q        " Call register 'q'
                            q       " Stop recording
                             @q     " Run the recursive macro
                               D    " Delete our extra line

```

# Answer
> 22 votes
# MATL, ~~20~~ 16 bytes

```
y-f1X-"t[]@X@q-(

```

Try it online! Or verify test cases: , , , , .

### Bonus

Modified code to *see the string being gradually shrunk* (offline compiler):

```
y-f1X-"tt.3Y.XxD[]@X@q-(].3Y.XxDvx

```

Or try it at MATL Online!

## Explanation

```
y        % Implicitly input string and char. Duplicate string onto top
-        % Subtract. Gives nonzero for chars in the input string that are
         % different from the input char
f        % Array of indices of nonzero values
1X-      % Remove 1 from that array. This gives an array of the indices of
         % chars to be removed from the string
"        % For each
  t      %   Duplicate previous string
  []     %   Push empty array
  @      %   Push index of char to be removed. But this index needs to be
         %   corrected to account for the fact that previous chars have
         %   already been removed...
  X@q-   %   ... So we correct by subtracting the 0-based iteration index
  (      %   Assign empty array to that position, to remove that char
         % Implicitly end for each
         % Implicitly display

```

# Answer
> 20 votes
# Haskell, 50 bytes

```
w@(a:x)%c|(d,_:y)<-span(==c)x=w:(a:d++y)%c|0<1=[w]

```

Defines a function `(%)` returning a list of strings.

### Explanation

`(%)` is called as `w%c`, with `w` being the input string, and `c` the character to keep. In short, this definition works by separating `w` into the first character (`a`) and the remainder (`x`), splitting `x` at the first occurrence of a character other than `c`, and recursively calling itself with that one character dropped.

```
w@(a:x)%c              -- define (%) with w separated into a and x.
 |(d,_:y)<-span(==c)x  -- split x; bind the string of `c` to d, and the rest
                       -- to _:y, dropping first character and calling the rest y.
  =w:(a:d++y)%c        -- if there was a character to drop, cons w onto the
                       -- sequence gained by recursively calling (%) with that
                       -- character removed (i.e. call with a:d++y).
 |0<1=[w]              -- if nothing needed to be dropped, the result sequence is
                       -- simply the one-element list [w]

```

# Answer
> 14 votes
## Retina, ~~28~~ 27 bytes

Byte count assumes ISO 8859-1 encoding.

```
;{G*1`
R1r`(?!^|.*¶?\1$)(.)

```

Try it online!

### Explanation

```
;{G*1`

```

There's a lot of configuration here. The stage itself is really just `G1``, which keeps only the first line, discarding the input character. `*` turns it into a dry run, which means that the result (i.e. the first line of the string) is printed without actually changing the string. `{` tells Retina to run both stages in a loop until the string stops changing and `;` prevents output at the end of the program.

```
R1r`(?!^|.*¶?\1$)(.)

```

This discards the first character which a) isn't at the beginning of the input, b) isn't equal to the separate input character.

# Answer
> 10 votes
# Perl 5, 29 bytes

I got 35 bytes using Strawberry Perl: 31 bytes, plus 1 for `-nE` instead of `-e`, plus 3 for space + `-i` (used for the single-letter input; the longer string is from STDIN).

```
chomp;say;s/(.)[^$^I]/$1/&&redo

```

However, I've no doubt this is doable without `chomp;` using `<<<`, which is 29 bytes, even though I can't test it myself using Strawberry.

```
say;s/(.)[^$^I]/$1/&&redo

```

Thus:

```
perl -im -nE'say;s/(.)[^$^I]/$1/&&redo' <<< "example"

```

# Answer
> 10 votes
## Pip, ~~22~~ ~~26~~ ~~24~~ 22 bytes

```
Lv+#Paa@oQb?++oPaRA:ox

```

Takes string as first command-line argument, character as second. Try it online!

### Explanation

Loops over characters of input; if the character equals the special character, move on to the next one; if not, delete it and print the string.

An ungolfed version (`a`, `b` get cmdline args; `o` starts with a value of `1`, `x` is `""`):

```
P a         Print a
L #a-1      Loop len(a)-1 times:
 I a@o Q b   If a[o] string-eQuals b:
  ++o         Increment o
 E {         Else:
  a RA: o x   In-place in a, Replace char At index o with x (i.e. delete it)
  P a         Print a
 }

```

Golfing tricks:

* The loop header for `L` is only evaluated once, so we can sneak the initial print in there. `#Pa-1` won't work because `P` is low-precedence (it would parse as `#P(a-1)`), but we can rearrange it to `v+#Pa`, using the `v` variable preinitialized to `-1`.
* The `RA:` operator returns the new value of `a`, so we can print that expression instead of having a separate `Pa` statement.
* Now both of the branches of the if statement are single expressions, so we can use the ternary operator `?` instead.

# Answer
> 8 votes
# Perl 6,  ~~47 40~~  38 bytes

```
->\a,\b{a,{S/^(."{b}"*:)./$0/}...^{$^a eq $^b}}

```

```
->\a,\b{a,{S/^(."{b}"*:)./$0/}...^&[eq]}

```

```
{$^b;$^a,{S/^(."$b"*:)./$0/}...^&[eq]}

```

## Expanded:

```
{       # lambda with two placeholder parameters ｢$a｣ and ｢$b｣

  $^b;    # declare second parameter

  $^a,    # declare first parameter, and use it to seed the sequence

  {       # bare block lambda with implicit parameter ｢$_｣
    S/      # string replace and return
      ^       # beginning of string
      (       # capture into ｢$0｣
        .       # the first character
        "$b"*   # as many ｢$b｣ as possible
        :       # don't allow backtracking
      )
      .       # any character ( the one to be removed )

    /$0/      # put the captured values back into place
  }

  ...^      # repeat that until: ( and throw away the last value )

  &[eq]     # the infix string equivalence operator/subroutine

}

```

The reason `...^` was used instead of `...` is that `&[eq]` wouldn't return `True` until the last value was repeated.

# Answer
> 8 votes
# Python 3, 72 bytes

```
def e(i,k):
 for r in i:
  if r!=k:i=i[0]+i[1:].replace(r,'',1);print(i)

```

Try it online!

```
e('','')

```

Go on a diet:

```

```

# Answer
> 7 votes
# Python 2, ~~71~~ 66 bytes:

```
f,m=input();k=f[0]
while f:a=f[0]==m;k+=f[0]*a;f=f[1+a:];print k+f

```

A full program. Takes 2 inputs through STDIN in the format `'<String>','<Char>'`.

Also, here is a recursive solution currently at **140 bytes**:

```
Q=lambda c,p,k='',j=1,l=[]:c and Q(c[1:],p,k+c[0]*(j<2)+c[0]*(c[0]==p),j+1,l+[k+c])or'\n'.join(sorted({*l},key=l.index))+('\n'+k)*(k not in l)

```

This one should be called in the format `print(Q('<String>','<Char>'))`.

# Answer
> 7 votes
# 05AB1E, ~~26~~ 25 bytes

```
¬ˆ[¦Ðg_#¬²k0Qi²ˆë¯J?,]¯J?

¬ˆ                         Put the first character into an array
  [                        While true
   ¦                       Remove the first character
    Ð                      Triplicate
     g_#                   if the string is empty, break
        ¬²k0Qi             if the first character is equal to the one specified in the input
              ²ˆ           Add it to the array
                ë          Else
                 ¯J?       Display the array
                    ,      Display the remaining string
                     ]     End while
                      ¯J?  Display the last string

```

Try it online!

Please note that `¬²k0Q` could be rewritten `¬²Q`, but for some reason it doesn't work when the current character is a quote mark: Q returns the actual string instead of a boolean and it causes an infinite loop.

This code can be golfed further since `¯J?` is duplicated. Moving this part in the loop would remove the duplication and would also allow to drop the closing square bracket.

# Answer
> 7 votes
## JavaScript (ES6), 74 bytes

```
(s,c)=>[...t=s.slice(1)].map(d=>c!=d?s+=`
`+s[0]+(t=t.replace(d,``)):s)&&s

```

# Answer
> 5 votes
# Ruby, ~~148~~ ~~139~~ ~~97~~ ~~90~~ ~~83~~ ~~77~~ 62 bytes

```
a,c=$*;p s=""+a;i=1;while d=s[i];(d!=c)?(s[i]="";p s):i+=1;end

```

Not sure if amateur code is accepted on this exchange but I'm interested in learning to code golf although I'm terrible at it, any help on how I'd get this program looking as small as the others here?

**EDIT:**

Replaced puts with p

Removed a tonne of whitespace and counted bytes correctly thanks to Wheat Wizard

Thanks to challenger5 went from `s=gets.chop;c=gets.chop;` to `s,c=gets.chop,gets.chop;`

replaced `then` with `;` and `gets.chop` with `gets[0]` thanks Mhutter!

Taking input as command line variables now, eg. `prog.rb helloworld l`

Thanks to numerous improvements by jeroenvisser101 replacing `a=s.dup` with `s=""+a` and the previous if statement `if s[i]!=c;s[i]="";p s;else i+=1;end` with `(d!=c)?(s[i]="";p s):i+=1;` huge improvement!

# Answer
> 4 votes
# JavaScript (ES6), 63 ~~64 69~~

Thanks to @Shaggy for shaving 1 byte!

Returning a single string with newlines

```
s=>c=>[...s].map((x,i,z)=>i&&x!=c&&(s+=`
`+z.join(z[i]='')))&&s

```

```
F=
s=>c=>[...s].map((x,i,z)=>i&&x!=c&&(s+=`
`+z.join(z[i]='')))&&s

function update() {
  var s=S.value,c=C.value[0]
  O.textContent=F(s)(c)
}

update()
```

```
<input id=S value='Hello world!' oninput='update()'>
<input id=C value='!' oninput='update()'>
<pre id=O></pre>
```

# Answer
> 4 votes
# c90, 129 125 bytes

with whitespace:

```
main(q, x)
{
    for (char **v = x, *a = v[1], *b = a, *c;*b++;)
        for (c = a; c == a | *c == *v[2] && *b != *v[2] && putchar(*c),
            ++c != b || *b != *v[2] && !puts(b););
}

```

without whitespace:

```
main(q,x){for(char**v=x,*a=v[1],*b=a,*c;*b++;)for(c=a;c==a|*c==*v[2]&&*b!=*v[2]&&putchar(*c),++c!=b||*b!=*v[2]&&!puts(b););}

```

ungolfed:

```
#include <stdio.h>
int main(int argc, char **argv)
{
    char *a = argv[1];
    for (char *b = a + 1; *b; b++) {
        if (*b == *argv[2]) {
            continue;
        }
        putchar(*a);
        for (char *c = a + 1; c != b; c++) {
            if (*c == *argv[2]) {
                putchar(*c);
            }
        }
        puts(b);
    }
}

```

This takes a pointer to the start of the string, and loops, iterating this pointer until it reaches the end of the string. Within the loop, it prints the first character, then any instances of the second argument it finds between the start of the string and the pointer. After this, it calls puts on the pointer, printing out the rest of the string.

This must be compiled on a system where sizeof(int) == sizeof(char\*). +3 bytes otherwise.

This is the first time I've tried code golfing here, so I'm sure there are some optimizations to be made.

# Answer
> 3 votes
# PHP, ~~88~~ ~~84~~ ~~86~~ ~~85~~ ~~82~~ ~~81~~ 78 bytes

1 byte saved thanks to @IsmaelMiguel, 3 bytes thanks to @user59178, 3 bytes inspired by @user59178

```
while($b=substr("$argv[1]\n",$i++))$a>""&$b[0]!=$argv[2]?print$a.$b:$a.=$b[0];

```

takes input from command line arguments; run with `php -r <code> '<string>' <character>`

---

* appends a newline to the input for an implicit final print.
That adds ~~5~~ 4 bytes of code, but saves on the output and an additional `echo$a;`.

# Answer
> 3 votes
# Dyalog APL, 27 bytes

`{×i←⊃1+⍸⍺≠1↓⎕←⍵:⍺∇⍵/⍨i≠⍳≢⍵}`

is the excluded character,  is the initial string

print argument; find index `i` of the first non- after the first char; if found, call recursively with `i` removed

# Answer
> 3 votes
# Mathematica, 64 bytes

```
Most@FixedPointList[StringReplace[#,b_~~Except@a:>b,1]&,a=#2;#]&

```

Anonymous function. Takes two strings as input, and returns a list of strings as output. Works by repeatedly removing the first non-instance of the character.

# Answer
> 3 votes
# 05AB1E, ~~26~~ ~~24~~ 23 bytes

Thanks @Kade for 2 bytes!
Thanks @Emigna for 1 byte!

```
¬UDvy²k0Êiy¡¬s¦yý«Xs«=¦

```

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

`y²k0Ê` could be `y²Ê` but the `"` messes it up.

This probably could be golfed more because `«` is repeated twice. Please leave a comment if you have any suggestions or ways to golf it down more.

# Answer
> 3 votes
# Java 10, ~~155~~ ~~140~~ ~~139~~ 124 bytes

```
c->s->{var r=s+"\n";for(int i=0;++i<s.length();)if(s.charAt(i)!=c)r+=(s=s.substring(0,i)+s.substring(i--+1))+"\n";return r;}

```

Try it online.

**Explanation:**

```
c->s->{          // Method with character and String parameters and String return-type
  var r=s+"\n";  //  Result-String, starting at the input-String with trailing new-line
  for(int i=0;++i<s.length();)
                 //  Loop over the characters of the String, skipping the first
    if(s.charAt(i)!=c)
                 //   If the current character and the input-character are equal
      r+=(s=s.substring(0,i)+s.substring(i--+1))
                 //     Remove this character from the String `s`
         +"\n";  //     And append the new `s` with trailing new-line to the result-String
  return r;}     //  Return the result-String

```

---

**Old 139 bytes recursive answer:**

```
void c(String s,int c){System.out.println(s);for(int i=1;i<s.length();)if(s.charAt(i++)!=c){c(s.substring(0,i-1)+s.substring(i),c);break;}}

```

-1 bytes thanks to *@Eugene*. (Next time make a comment instead of editing someone else's post, please.)

Try it online.

**Explanation:**

```
void c(String s,int c){     // Method with String and integer parameters and no return-type
  System.out.println(s);    //  Print the input-String with trailing new-line
  for(int i=1;i<s.length();)//  Loop over the characters of the String, skipping the first
    if(s.charAt(i++)!=c){   //   If the current character and the input-character are equal
      c(s.substring(0,i-1)+s.substring(i),c);
                            //    Remove this character, and do a recursive call
      break;}}              //    And stop the loop

```

# Answer
> 2 votes
# C#, ~~135~~ ~~138 :(~~ 137 bytes

Golfed:

```
IEnumerable<string>F(string s,char c){int i=1,l;for(;;){yield return s;l=s.Length;while(i<l&&s[i]==c)i++;if(i==l)break;s=s.Remove(i,1);}}

```

Ungolfed:

```
    IEnumerable<string> F(string s, char c)
    {
        int i = 1, l;

        for (;;)
        {
            yield return s;

            l = s.Length;

            while (i < l && s[i] == c)
                i++;

            if (i == l)
                break;

            s = s.Remove(i, 1);
        }
    }

```

Function returns collection of strings.

EDIT1: @psycho noticed that algorithm was not implemented properly.

EDIT2: Created variable for `s.Length`. One byte saved thanks to @TheLethalCoder.

# Answer
> 2 votes
# C#, 122 117 112 bytes

```
IEnumerable F(string s,char c){for(int i=0;i<s.Length;++i)if(i<1||s[i]!=c)yield return i>0?s=s.Remove(i--,1):s;}

```

Ungolfed :

```
public IEnumerable F(string s, char c) {
    for (int i = 0; i < s.Length; ++i) {
        if (i < 1 || s[i] != c)
            yield return i > 0 ? s = s.Remove(i--, 1) : s;
    }
}

```

Returns a collection of strings.

# Answer
> 2 votes
## Pyke, ~~26~~ ~~19~~ 17 bytes

```
jljjhF3<Q/Q*jih>s

```

Try it here!

```
                  - Q = input
j                 - j = input_2
 ljjhF3           - for (i, j, j[0]) for i in range(len(j))
       <          -     j[:i]
        Q/        -    ^.count(Q)
          Q*      -   ^*Q
                s -  sum(j[0], ^, V)
            jih>  -   j[i+1:]

```

# Answer
> 2 votes
**TSQL, 127 bytes(Excluding variable definitions)**

```
DECLARE @1 VARCHAR(100)='codegolf.stackexchange.com'
DECLARE @2 CHAR(1) = 'o'

DECLARE @ char=LEFT(@1,1)WHILE patindex('%[^'+@2+']%',@1)>0BEGIN SET @1=STUFF(@1,patindex('%[^'+@2+']%',@1),1,'')PRINT @+@1 END

```

Formatted:

```
DECLARE @1 VARCHAR(100) = 'codegolf.stackexchange.com'
DECLARE @2 CHAR(1) = 'o'
DECLARE @ CHAR = LEFT(@1, 1)

WHILE patindex('%[^' + @2 + ']%', @1) > 0
BEGIN
    SET @1 = STUFF(@1, patindex('%[^' + @2 + ']%', @1), 1, '')

    PRINT @ + @1
END

```

# Answer
> 2 votes
# **Python 2 - ~~65~~ 73 Bytes**

```
lambda s,c:[s[0]+c*s[1:i].count(c)+s[i+1:]for i in range(len(s))]

```

And a **76 Bytes** recursive solution, because despite being longer than the firt one, I kinda like it better:

```
f=lambda s,c,i=1:s[i:]and[[s]+f(s[:i]+s[i+1:],c,i),f(s,c,i+1)][s[i]==c]or[s]

```

# Answer
> 2 votes
## Racket 194 bytes

```
(let p((s s)(n 1)(t substring)(a string-append))(displayln s)(cond[(>= n(string-length s))""]
[(equal? c(string-ref s n))(p(a(t s 0 n)(t s n))(+ 1 n)t a)][else(p(a(t s 0 n)(t s(+ 1 n)))n t a)]))

```

Ungolfed:

```
(define (f s c)
  (let loop ((s s)
             (n 1))
    (displayln s)
    (cond
      [(>= n (string-length s))""]
      [(equal? c (string-ref s n))
       (loop (string-append (substring s 0 n) (substring s n))
             (add1 n))]
      [else
       (loop (string-append (substring s 0 n) (substring s (add1 n)))
             n)])))

```

Testing:

```
(f "Test cases" #\s)
(f "codegolf.stackexchange.com" #\e)

```

Output:

```
Test cases
Tst cases
Tst cases
Ts cases
Tscases
Tsases
Tsses
Tsses
Tsss
Tsss
""
codegolf.stackexchange.com
cdegolf.stackexchange.com
cegolf.stackexchange.com
cegolf.stackexchange.com
ceolf.stackexchange.com
celf.stackexchange.com
cef.stackexchange.com
ce.stackexchange.com
cestackexchange.com
cetackexchange.com
ceackexchange.com
ceckexchange.com
cekexchange.com
ceexchange.com
ceexchange.com
ceechange.com
ceehange.com
ceeange.com
ceenge.com
ceege.com
ceee.com
ceee.com
ceeecom
ceeeom
ceeem
ceee
""

```

# Answer
> 2 votes
# Swift 3 - ~~151~~ 147 bytes

Swift isn't the ideal language for golfing, particularly when it relates to string indexing. This is the best I could do:

```
func c(a:String,b:String){print(a);var q=Array(a.characters),i=1;while i<q.count{if "\(q[i])" != b{q.remove(at:i);c(a:String(q),b:b);break};i=i+1}}

```

Unfortunately, Swift needs spaces around `!=` (but not for `==`), and Swift 3 dropped the `++` operator. The trick for both of these is to convert to a character array which allows integer indexing, and using string interpolation of a character to convert back to a `String` (`"\(c)"`).

Ungolfed:

```
func c(a:String, b:String) {
    print(a)
    var q = Array(a.characters)
    var i = 1
    while i < q.count {
        if "\(q[i])" != b {
            q.remove(at:i)
            c(a: String(q), b: b)
            break
        }
        i=i+1
    }
}

```

---

### Previous, non-recursive solution

```
func c(a:String,b:String){var q=Array(a.characters),e={q.removeFirst()},z="\(e())";print(a);while !q.isEmpty{"\(e())"==b ? z=z+b : print(z+String(q))}}

```

```
func c(a:String, b:String) {
    var q = Array(a.characters)
    var z = "\(q.removeFirst())"
    print(a)
    while !q.isEmpty {
        if "\(q.removeFirst())" == b {
            z = z + b
        }else{
            print(z + String(q))
        }
    }
}

```

# Answer
> 2 votes
# Vyxal, 77 bits<sup>v1</sup>, 9.625 bytes

```
ḣ≬‡⁰≠Ǒ⟇↔Ṡ+

```

Try it Online!

## Explained

The very first explanation generated using Luminespire, a currently work-in-progress explanation formatting assistant. Now with metadata!

```
ḣ≬‡⁰≠Ǒ⟇↔Ṡ+
ḣ           # Push first character of input, then all of input minus first character
 ≬     ↔    # Repeat and collect results of applying the following on the top of the stack until invariant:
  ‡  Ǒ      #   Find the first index of:
   ⁰≠       #      a character that isn't the second input
      ⟇     #   Remove that character from the top of the stack
        Ṡ   # Convert each item to a string via vectorised summation
         +  # Prepend the first letter to each

```

# Answer
> 2 votes
# C (gcc), 70 bytes

```
f(x,v,i)char*x,*i;{for(puts(i=x);*++i;)*i-v&&puts(x,strcpy(i--,i+1));}

```

Try it online!

# C (gcc), 65 bytes(32-bit) by c--

```
f(x,v){char*i;for(puts(i=x);*++i;)*i-v&&puts(x,strcpy(i--,i+1));}

```

Try it online!

# Answer
> 1 votes
# Mathematica, 78 bytes

Damn you Martin Ender, I was almost first :p

```
(i=2;a={c=#};While[i<=Length@c,If[c[[i]]==#2,i++,c=c~Drop~{i};a=a~Append~c]];a)&

```

Unnamed function; straightforward implementation with a `While` loop and a few temporary variables.

# Answer
> 1 votes
# JavaScript ES6, 89 bytes

I thought this would be an easy challenge, but I'm pretty sure I'm missing something here..

Uses recursion and returns an array of strings

```
(c,i=1,r)=>f=a=>a[i]?a[i++]==c?f(a):f(g=a.slice(0,i-1)+a.slice(i--),(r=r||[a]).push(g)):r

```

```
F=
  (c,i=1,r)=>f=a=>a[i]?a[i++]==c?f(a):f(g=a.slice(0,i-1)+a.slice(i--),(r=r||[a]).push(g)):r

G=_=>A.value.length>1 && (O.innerHTML = F(E.value)(A.value).join`
`)

G()
```

```
<input id=A oninput='G()' value='alphabet'>
<input id=E oninput='G()' value='a'>
<pre id=O>
```

# Answer
> 1 votes
# Python 3, ~~67~~ ~~63~~ 142 Bytes

```
a,b,l1=input(),input(),0
for n in range(len(a)):
    l2=l1
    l1=''.join([a[:len(a)-n]]+[x for x in a[len(a)-n:] if x==b])
    if l2!=l1: print(l1)

```

It takes a as the string and b as the char, then goes through each letter in the string and adds it to the list if it's the first one or the character. Then it joins and prints.

**EDIT**: Fixed the problem mentioned by @R. Kap where it included copies of the first character as well, and shortened it to 63 bytes in the meantime.

**EDIT 2**: Now I realize you have to print out each string along the way. Brilliant. Well, this code is no longer golfed, but rather driven to the hole on a moped.

# Answer
> 1 votes
# Groovy, 34 bytes

```
{a,b->a.inject{i,r->i+=r==b?b:""}}

```

# Answer
> 1 votes
# JavaScript, 91 bytes

```
function(p,k){for(var i=1;i<p.length;)p[i]!=k?console.log(p=p.slice(0,i)+p.slice(i+1)):i++}

```

<sup>Huge thanks to ETHproductions for the help!</sup>

# Answer
> 1 votes
# Java 8, 104 bytes

## Golfed:

```
(x,y)->{String q="(.["+y+"]*)",s=x;while(!x.matches(q))s+="\n"+(x=x.replaceFirst(q+".","$1"));return s;}

```

## Ungolfed

```
(x, y) -> {
        String q = "(.[" + y + "]*)", s = x; // Store pattern for matching, and start our 'list' of strings.
        while (!x.matches(q)) {              // While our string doesn't fit a valid 'Ceeeeee' pattern...
            s += "\n" + (                    // We append our list of strings with a newline and...
            x = x.replaceFirst(q + ".", "$1")// A version of the string where the next character that isn't our given character is removed through regex replacement.
            );
        }
        return s;                            // We then return the newline-delimited string.
    }

```

## Output:

```
Hello world!
Hllo world!
Hll world!
Hllworld!
Hllorld!
Hllrld!
Hllld!
Hlll!
Hlll

```

See it here!

Function is a lambda (BiFunction used in test code). Takes a String and a Character, and returns a String.

# Answer
> 1 votes
# SmileBASIC, 65 bytes

```
INPUT S$,C$?S$@L
IF I&&S$[I]!+C$THEN S$[I]=""?S$ELSE I=I+1
GOTO@L

```

# Answer
> 1 votes
# Excel, 52 Bytes

```
=LEFT(A1)&REPT(A2,LEN(A1)-LEN(SUBSTITUTE(A1,A2,"")))

```

where `A1` and `A2` are the string and the substitute letter respectively

I realise that may not actually answer the question, the wording is functions *may return arrays* but I'm guessing I need all the intermediate steps. So I've added

# VBA, ~~142~~ 137 (-4) bytes

```
Sub x(a, b)
For i = 2 To Len(a)
c = Mid(a, i, 1)
If c = "" Then End 'or d = 1 / Len(c) but then we quit on an error
If b<>c Then a = Replace(a, c, "", , 1): i = 1: Debug.?a
Next
End Sub

```

Which I think is the right byte count but I'm not sure how extra lines are treated. called in the same way as the Excel version. Returns all the steps in the Immediate Window

# Answer
> 1 votes
# Japt `-R`, ~~18~~ 16 bytes

```
¬ËUoÈ¥Vª!YªY>E
â

```

Try it online!

### Unpacked & How it works

```
Uq mDEF{UoXYZ{X==V||!Y||Y>E
Uâ

Uq mDEF{    Split input into chars and map...
  UoXYZ{      Filter on the original input...
    X==V||      Keeping chars same as 2nd input (V),
    !Y||        1st char,
    Y>E         and indices exceeding outer index
\n          Close all braces implicitly and save the result to U
Uâ          Take unique elements from U

```

Turns out that trying to use regex is way too verbose here.

The `-R` flag joins the resulting array of strings with newline, saving three bytes `<space>qR` at the end. Also, this code exploits the JS feature of `Array.map` and `Array.filter`, where the index is passed as the 2nd argument (`E` and `Y` in the code above).

# Answer
> 1 votes
# Python 3, 135 bytes

```
(lambda a:print(a[0])or[a.__setitem__(0,a[0][0]+a[0][1:].replace(x,'',1))or print(a[0]) for x in a[0][1:] if x!=a[1]])([input(),input()])

```

# Answer
> 1 votes
# Python 3: ~~108~~ 99 bytes

```
def g(s,o):
 r,p=s[0],print
 for i in range(1,len(s)):
  if s[i]==o:r+=s[i]
  else:p(r+s[i:])
 p(r)

```

Then invoke the function with:

```
g('alphabet', 'a')

```

Output:

```
alphabet
aphabet
ahabet
aabet
aaet
aat
aa

```

Try it online!

# Answer
> 1 votes
# Vyxal, 12 bytes

```
$o(…:⁰v≠TḢh⋎

```

Try it Online!

### Explained

```
$o(…:⁰v≠TḢh⋎
$            # swap top 2 items
 o           # remove
  (          # loop
   …         # print without popping
    :        # duplicate
     ⁰       # last input
      v      # vectorise
       ≠     # not equal
        T    # truthy indices
         Ḣ   # remove head [0]
          h  # head
           ⋎ # bitwise or

```

# Answer
> 1 votes
# Thunno 2, 18 bytes

```
Ḣȥ(ȤJ¢£x;ḢYẊy¹=?yȥ

```

Attempt This Online!

#### Explanation

```
Ḣȥ(ȤJ¢£x;ḢYẊy¹=?yȥ  # Implicit input
Ḣȥ                  # Extract the first character, and add it to the global array
  (     ;           # While loop
   ȤJ               # (condition)   Join the global array
     ¢              #               Print it with no newline
      £             #               Print top of stack with a newline
       x            #               Push x (initialised to 1)
         Ḣ          # (body)        Extract the first character
          Y         #               Pop and store in y
           Ẋ        #               Without popping, store the rest in x
            y       #               Push y again
             ¹=     #               Is it equal to the second input?
               ?    #               If it is:
                yȥ  #                 Add y to the global array

```

# Answer
> 1 votes
# Python 3, 94 bytes

```
def f(n,s,d=1):
 print(n)
 if set(n[1:])-{s}:
  if n[d]==s:d+=1
  n=n[:d]+n[d+1:];f(n,s,d)

```

Happy to have broken 100 bytes but I'm sure it could be golfed down.

# Answer
> 0 votes
# Python 3, 87 83 bytes

```
s=open(0).read()
p,c,s=s[0],s[-2],s[:-3]
for h in s:p+=s[:h==c];s=s[1:];print(p+s)

```

Explanation: I chose python 3 instead of python 2, because it allows to use file descriptors in `open` (and `0` is the descriptor of the standard input). In each loop iteration `p` keeps track of stored prefix. `s[:h==c]` works as follows: boolean expression `h==c` is casted into integer (0 or 1), and then the corresponding amount of characters from the beginning of `s` are taken.

P.S. The loop in the initial version was:

```
for h in s:
 if h==c:p+=h
 s=s[1:];print(p+s)

```

# Answer
> 0 votes
# JavaScript (ES2015) - 86 bytes

```
let f=([a,...s],c,r=[])=>r[0]==a+s?r:f(a+s.replace(eval(`/[^${c}]/`),''),c,[a+s,...r])

```

# Answer
> 0 votes
# C, ~~83~~ 79 bytes

```
char x[];i;m(char*v,c){for(x[i]=*v;*v;)*++v-c?printf("%s%s\n",x,v):(x[++i]=c);}

```

# Answer
> 0 votes
# sed, 76 (code) + 3 (-nr flags) = 79 bytes

```
N;s/(.*)\n(.).*/\2\1/
:L
h;s/.//;p;x
/^(.)(.\1*)$/q
s/^(.)(.\1*)./\1\2/
b L

```

Commented:

```
# Read in both lines, and swap the order so we can use
# back references to check for the special character
N;s/(.*)\n(.).*/\2\1/

:L

# Erase the first character (temporarily) and print the line
h;s/.//;p;x

# Terminate once only the second character in the buffer doesn't match the first
/^(.)(.\1*)$/q

# Erase the first non-matching character
s/^(.)(.\1*)./\1\2/

b L

```

Unfortunately, back references aren't permitted within character classes, so we're forced to repeat ourselves a bit on the last three lines. If it were possible, we could replace `b L` with `t L`, and remove `/^(.)(.\1*)$/q` entirely, thus dropping this down to 65 bytes.

Usage:

```
$ cat in
Test Cases
s
$ sed -nrf foo.sed < in
Test Cases
Tst Cases
Ts Cases
TsCases
Tsases
Tsses
Tsss

```

# Answer
> 0 votes
# Python 3, ~~94~~ 93 Bytes

```
b=list(input())
c=input()
i=1
while i<len(b):
 while b[i]==c:i+=1
 b.pop(i);print(''.join(b))

```

Thanks to @Challenger5 for pointing out that I had misread the question

# Answer
> 0 votes
# Scala, 107 82 bytes

Thanks to corvus\_192 for a scala code-golf discussion link (appreciated!)

## Golfed

```
1.to(s.size-1)./:(s take 1)((p,i)=>if(s(i)!=c){println(p+s.drop(i));p}else p+s(i))

```

## Ungolfed

```
(1 until s.length).foldLeft((s.take(1), List[String]())) { case ((prefix, acc), i) =>
  s.charAt(i) match {
    case char if char != c => (prefix, acc :+ (prefix + s.drop(i)))
    case char => (prefix + char, acc)
  }
}._2.foreach(println)

```

Using `foldLeft` means we can 'accumulate' the prefix, and print a new line when the next character does not equal 'c'. Short-hand for foldLeft is `/:`

Ungolfed, we can also accumulate the results and just print the results at the end (no side effects), plus the match statement makes it a little cleaner

# Answer
> 0 votes
# C#, 91 bytes

```
s=>c=>{var r=s;for(int i=1;i<s.Length;)if(s[i++]!=c)r+="\n"+(s=s.Remove(--i,1));return r;};

```

Anonymous function which merges each line of output into a string and returns the result, since the function `may return an array of strings` instead of `will return`.

Full program with ungolfed method and test cases:

```
using System;

namespace CeeeeeeeeProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, Func<char, string>> f =
            s => c =>
            {
                var r = s;
                for (int i = 1; i < s.Length; )
                    if (s[i++] != c)
                        r += "\n" + (s = s.Remove(--i, 1));
                return r;
            };

            // test cases:
            Console.WriteLine(f("codegolf.stackexchange.com")('e'));
            Console.WriteLine(f("Test Cases")('s'));
            Console.WriteLine(f("Make a \"Ceeeeeeee\" program")('e'));
            Console.WriteLine(f("Hello World!")('!'));
            Console.WriteLine(f("Hello World!")('z'));
            Console.WriteLine(f("alphabet")('a'));
            Console.WriteLine(f("upperCASE")('e'));
        }
    }
}

```

Alternatively, an anonymous function with no return type which will print the output to stdout line by line will count **105 bytes**:

```
(s,c)=>{Console.WriteLine(s);for(int i=1;i<s.Length;)if(s[i++]!=c)Console.WriteLine(s=s.Remove(--i,1));};

```

# Answer
> 0 votes
# Bash \+ Unix utilities, ~~89~~ ~~88~~ ~~85~~ ~~84~~ 82 bytes

```
z=$1
for((;${#z}-n;)){
echo "$z"
n=${#z}
z=`sed "s/^\(.[$2]*\)[^$2]/\1/"<<<"$z"`
}

```

Try it online!

Note that you can't write just `$2` instead of `[$2]` in the regex; if you do that, it will work most of the time, but it will fail if the second argument is a special character like `*` or `/`.

*Edit: Thanks to @ckjbgames for 3 bytes.*

# Answer
> 0 votes
# Clojure, 123 bytes

```
(fn[[f & p]l](loop[[n & m :as r]p a f](println(str a(apply str r)))(if m(recur(if(= n l)(rest m)m)(if(= n l)(str a n)a)))))

```

Definitely not optimal. I tried getting rid of the two `if`s in the `recur`, but the inclusion of a `let` made it bigger!

Loops over the string, popping the first char. If it equals the supplied character, it's added to the accumulator, and dropped from the remaining string.

```
(defn ceee [[first-char & rest-phrase] letter] ; Deconstruct the first letter off right from the parameter list

  (loop [[next-char & rest-remaining :as r] rest-phrase ; Deconstruct the remaining string apart
         acc first-char] ; Keep track of the letters to show at the start

    (println (str acc (apply str r))) ; Print the prefix accumulator, then the remaining phrase

    (if rest-remaining ; Recur if there's part of the phrase left
      (recur (if (= next-char letter)
               (rest rest-remaining)
               rest-remaining)
             (if (= next-char letter)
               (str acc next-char)
               acc)))))

```

# Answer
> 0 votes
# PHP, 84 Bytes

a REGEX based answer

```
for($a=$argv[$c=1];$c;$a=preg_replace("#^(.+)[^$argv[2]]#","$1",$a,1,$c))echo"$a\n";

```

You can use the second input as REGEX for chars that are not removed

Examples

# Answer
> 0 votes
# Yabasic, 102 bytes

An Anonymous function that takes input as two strings and outputs to the console.

```
Input""s$,v$
For i=2To Len(s$)If Mid$(s$,i,1)<>v$Then?s$:s$=Mid$(s$,1,i-1)+Mid$(s$,i+1):i=1Fi
Next
?s$

```

Try it online!

# Answer
> 0 votes
# Stax, 10 bytes

```
Ä▬ä+QÜ├┌9◘

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
Q       print the input string without popping
1:/     split after the first character, and push both parts separately
        e.g. "H" "ello World!"
c,-     remove instances of the character from the second part
m       for each remaining character, run the rest of the program and print the result
  |-    remove the first instance of the character
  b+    copy both strings on the stack and append

```

Run this one

# Answer
> 0 votes
# PowerShell, ~~94~~ ~~89~~ ~~84~~ 79 bytes

```
param($s,$c)$s
for(;++$y-lt$s.length){if($s[$y]-cne$c){($s=$s.remove($y--,1))}}

```

Try it online!

Works by just chipping out a letter, starting at the 2nd, if it doesn't match and prints the resulting string; otherwise just increments i and this goes until it falls off. Had to use the case-sensitive -ne because PowerShell is insensitive by default. It takes a string and a char.

# Answer
> 0 votes
# Pascal (FPC), 195 bytes

```
var s:string;c:char;i,j:word;begin readln(s);read(c);i:=2;while i<length(s)+1do begin if c=s[i]then i:=i+1 else begin writeln(s);for j:=i to length(s)do s[j]:=s[j+1];Dec(s[0])end;end;write(s)end.

```

Try it online!

String is in first line of input, character is in second line of input.

# Answer
> 0 votes
# Assembly (MIPS, SPIM), 271 bytes

```
.text
.globl main
main:
lw $4 8($5)
lb $10 ($4)
lw $8 4($5)
move $9 $8
i:
move $4 $8
li $2 4
syscall
k:
move $4 $9
addi $9 1
lb $2 ($9)
beq $2 $10 k
beq $2 $0 e
l:
lb $2 ($4)
sb $2 1($4)
addi $4 -1
bge $4 $8 l
li $4 10
li $2 11
syscall
addi $8 1
j i
e:
li $2 10
syscall

```

Try it online!

I've realized when not doing syscalls, the 'a' and 'v' registers are free, which allowed me to save a few bytes. It's also a huge code smell, but this is code golf, so that's irrelevant. Takes the input via command-line arguments (I could do STDIN equivalent, but that costs more), and outputs to system out.

A detailed version that explains what all this does can be found here

# Answer
> 0 votes
# Rockstar, 108 bytes

Takes the string as the first line of input and the character as the second.

```
listen to S
listen to K
say S
cut S
roll S in F
while S
roll S in N
if N's K
let F be+N

join S in O
say F+O

```

Try it (Code will need to be pasted in)

# Answer
> 0 votes
# Ruby, 53 bytes

```
->(a,c){puts a;puts a while a.sub! /(?!^)[^#{c}]/,''}

```

Ungolfed

```
->(a,c) do # Define a lambda with 2 arguments, the string and the character
  puts a # output the string unchanged
  while( # Start a loop
    # continue until this replacement did not replace anything
    a.sub!( # replace in place
      # the first occurrence of the character in the string
      # other than the beginning of the string
      /(?!^)[^#{c}]/,
      # with nothing
      ''
    )
  ) do
    puts a # if replaced something, output the remaining string
  end
end

```

The double `puts a` seems redundant and annoys me, but couldn't figure out a way to improve it.

# Answer
> 0 votes
# Stax, 16 bytes

```
Å<4R@Γ↓ α¿εN~;è<

```

Run and debug it

## Approach

It uses repeated application of a regex-based replacement with callback. For example, if the target char is `e`, then it uses the regex `.[^e].*`. In the callback, it removes the character at position 1. It repeats this until no further replacement is possible.

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


title: Excessive Integers

text:
# Question
Title: Excessive Integers
For a *positive* integer `n` with the prime factorization `n = p1^e1 * p2^e2 * ... pk^ek` where `p1,...,pk` are primes and `e1,...,ek` are positive integers, we can define two functions:

* `Ω(n) = e1+e2+...+ek` the number of prime divisors (counted with multiplicity) (A001222)
    + `ω(n) = k` the number of distinct prime divisors. (A001221)

With those two functions we define the *excess* `e(n) = Ω(n) - ω(n)` (A046660). This can be considered as a measure of how close a number is to being squarefree.

### Challenge

For a given positive integer `n` return `e(n)`.

### Examples

For `n = 12 = 2^2 * 3` we have `Ω(12) = 2+1` and `ω(12) = 2` and therefore `e(12) = Ω(12) - ω(12) = 1`. For any squarefree number `n` we obivously have `e(n) = 0`. The first few terms are

```
1       0
2       0
3       0
4       1
5       0
6       0
7       0
8       2
9       1
10      0
11      0
12      1
13      0
14      0
15      0

```

Some more details in the OEIS wiki.

# Answer
# MATL, ~~7~~ 5 bytes

```
Yfd~s

```

Try it online! Or verify all test cases.

### Explanation

```
Yf    % Implicit input. Obtain prime factors, sorted and with repetitions
d     % Consecutive differences
~     % Logical negate: zeros become 1, nonzeros become 0
s     % Sum. Implicit display

```
> 7 votes

# Answer
# Brachylog, 11 bytes

```
$pPd:Pr:la-

```

Try it online!

### Explanation

```
$pP            P is the list of prime factors of the Input
  Pd           Remove all duplicates in P
    :Pr        Construct the list [P, P minus duplicates]
       :la     Apply "length" to the two elements of that list
          -    Output is the subtraction of the first element by the second one

```
> 7 votes

# Answer
# Mathematica, 23 bytes

```
PrimeOmega@#-PrimeNu@#&

```

Very boring. `FactorInteger` already takes up 13 bytes, and I can't see much that can be done with the remaining 10.
> 7 votes

# Answer
# Jelly, 5 bytes

```
ÆfI¬S

```

Try it online!

Verify all testcases.

Port of Luis Mendo's answer in MATL.

```
ÆfI¬S

Æf     Implicit input. Obtain prime factors, sorted and with repetitions
  I    Consecutive differences
   ¬   Logical negate: zeros become 1, nonzeros become 0
    S  Sum. Implicit display

```
> 5 votes

# Answer
# J, ~~11~~ 10 bytes

Saved 1 byte thanks to Jonah.

```
1#.1-~:@q:

```
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
Òg¹fg-

```

**Explanation**

```
Òg      # number of prime factors with duplicates
     -  # minus
  ¹fg   # number of prime factors without duplicates

```

Try it online!
> 3 votes

# Answer
# Haskell, 65 bytes

```
(c%x)n|x>n=c|mod n x>0=c%(x+1)$n|y<-div n x=(c+0^mod y x)%x$y
0%2

```
> 3 votes

# Answer
# 05AB1E, 4 bytes

```
Ò¥_O

```

Port of *@LuisMendo*'s MATL answer.

Try it online or verify the first 15 test cases.

**Explanation:**

```
Ò       # Get all prime factors with duplicates from the (implicit) input
        # (automatically sorted from lowest to highest)
 ¥      # Get all deltas
  _     # Check if it's equal to 0 (0 becomes 1; everything else becomes 0)
   O    # Take the sum (and output implicitly)

```
> 3 votes

# Answer
# Husk, ~~5~~ 4 bytes

```
ΣẊ=p

```

Try it online!

-1 byte from Dominic Van Essen.
> 3 votes

# Answer
# Pyth, 7 bytes

```
-lPQl{P

```

Try it online.
> 2 votes

# Answer
# C, 74 bytes

```
f(n,e,r,i){r=0;for(i=2;n>1;i++,r+=e?e-1:e)for(e=0;n%i<1;e++)n/=i;return r;}

```

Ideone it!
> 2 votes

# Answer
# Python 2, ~~57~~ 56 bytes

```
f=lambda n,k=2:n/k and[f(n,k+1),(n/k%k<1)+f(n/k)][n%k<1]

```

*Thanks to @JonathanAllan for golfing off 1 byte!*

Test it on Ideone.
> 2 votes

# Answer
# Python 2, ~~100~~ ~~99~~ ~~98~~ 96 bytes

```
n=input()
i=2
f=[]
while i<n:
 if n%i:i+=1
 else:n/=i;f+=i,
if-~n:f+=n,
print len(f)-len(set(f))

```

Most of the code is taken up by a golfed version of this SO answer, which stores the prime factors of the input in `f`. Then we simply use set manipulation to calculate the excess factors.

*Thanks to Leaky Nun for saving ~~1~~ 3 bytes!*
> 1 votes

# Answer
# Brachylog, 11 bytes

```
$p@b:la:-a+

```

Try it online!

Verify all testcases. (The wrapper is longer than the function...)

```
$p@b:la:-a+

$p            prime factorization
  @b          group blocks of equal elements
    :la       length of each
       :-a    each minus 1
          +   sum

```
> 1 votes

# Answer
## Javascript (ES6), ~~53~~ ~~51~~ 46 bytes

```
e=(n,i=2)=>i<n?n%i?e(n,i+1):e(n/=i,i)+!(n%i):0

```

*Saved 5 bytes thanks to Neil*

Example:

```
e=(n,i=2)=>i<n?n%i?e(n,i+1):e(n/=i,i)+!(n%i):0

// computing e(n) for n in [1, 30]
for(var n = 1, list = []; n <= 30; n++) {
  list.push(e(n));
}
console.log(list.join(','));
```
> 1 votes

# Answer
# S.I.L.O.S, 113 bytes

```
readIO
t=2
lbla
e=0
GOTO b
lblc
i/t
e+1
lblb
m=i
m%t
n=1
n-m
if n c
d=e
d/d
e-d
r+e
A=i
A-1
t+1
if A a
printInt r

```

Try it online!

A port of my answer in C.
> 1 votes

# Answer
# Bash, 77 bytes

```
IFS=$'\n '
f=(`factor $1`)
g=(`uniq<<<"${f[*]}"`)
echo $((${#f[*]}-${#g[*]}))

```

Complete program, with input in `$1` and output to stdout.

We set `IFS` to begin with a newline, so that the expansion `"${f[*]}"` is newline-separated. We use arithmetic substitution to print the difference between the number of words in the factorisation with the result of filtering through `uniq`. The number itself is printed as a prefix by `factor`, but it is also present after filtering, so falls out in the subtraction.
> 1 votes

# Answer
# Japt, 6 bytes

```
k äÎxÌ

```

Try it

```
k äÎxÌ     :Implicit input of integer
k          :Prime factors
  ä        :Consecutive pairs reduced by
   Î       :  Signs of differences (0 or -1)
    x      :Sum of
     Ì     :  Signs of differences with -1 (0 -> 1 and -1 -> 0)

```
> 1 votes

# Answer
# Factor \+ `math.primes.factors math.unicode`, 40 bytes

```
[ group-factors unzip Σ swap length - ]

```

Attempt This Online!

```
               ! 12
group-factors  ! { { 2 2 } { 3 1 } }
unzip          ! { 2 3 } { 2 1 }
Σ              ! { 2 3 } 3
swap           ! 3 { 2 3 }
length         ! 3 2
-              ! 1

```
> 1 votes

# Answer
# Pyt, 4 bytes

```
ḋ₋¬Ʃ

```

Try it online!

Port of Leaky Nun's Jelly answer
> 1 votes

# Answer
# Haskell, 87 bytes

```
import Data.Numbers.Primes
import Data.List
x=(\x->length x-length(nub x)).primeFactors

```

Try it online!
> 1 votes

# Answer
# Kamilalisp, 15 bytes

```
[-&[⍴] #0 ⊙]@⋔⌹

```

Attempt This Online!
> 1 votes

# Answer
# Nekomata, 3 bytes

```
ƒ←∑

```

Attempt This Online!

```
ƒ       Factor; returns a list of unique prime factors and a list of their exponents
 ←      Decrement the exponents
  ∑     Sum

```
> 1 votes

# Answer
# Ruby `-rprime`, 31 bytes

```
->n{n.prime_division.sum{_2-1}}

```

Attempt This Online!
> 1 votes

# Answer
# Python, (with sympy) 66 bytes

```
import sympy;lambda n:sum(x-1for x in sympy.factorint(n).values())

```

`sympy.factorint` returns a dictionary with factors as keys and their multiplicities as values, so the sum of the values is `Ω(n)` and the number of values is `ω(n)`, so the sum of the decremented values is what we want.
> 0 votes

# Answer
# GNU sed + coreutils, 55 bytes

(including +1 for `-r` flag)

```
s/^/factor /e
s/ ([^ ]+)(( \1)*)/\2/g
s/[^ ]//g
y/ /1/

```

Input in decimal, on stdin; output in unary, on stdout.

## Explanation

```
#!/bin/sed -rf

# factor the number
s/^/factor /e
# remove first of each number repeated 0 or more times
s/ ([^ ]+)(( \1)*)/\2/g
# count just the spaces
s/[^ ]//g
y/ /1/

```
> 0 votes

# Answer
**C, 158**

```
#define G(a,b) if(a)goto b
#define R return
f(n,i,j,o,w){if(!n)R 0;o=w=i=j=0;a:i+=2;b:if(n%i==0){++j;G(n/=i,b);}o+=!!j;w+=j;i+=(i==2);j=0;G(i*i<n,a);R w-o;}

```

In the start there is the goto instruction... even if this is more long than yours it is more readable and right \[if i not consider n too much big...\] one Language that has 10000 library functions is wrost than a Language that with few, 20 or 30 library functions can do all better \[because we can not remember all these functions\]

```
#define F for
#define P printf

main(i,r)
{F(i=0; i<100; ++i)
   r=f(i,0,0,0,0),P("[%u|%u]",i,r);
 R  0;
}

/*
 158
 [0|0][1|0][2|0][3|0][4|1][5|0][6|0][7|0][8|2]
 [9|0][10|0][11|0][12|1][13|0][14|0][15|0][16|3]
 [17|0][18|0][19|0][20|1][21|0][22|0][23|0][24|2][25|1][26|0][27|0] [28|1]
 [29|0][30|0][31|0][32|4][33|0][34|0][35|0][36|1]
 [37|0][38|0][39|0][40|2][41|0]
 */

```
> 0 votes

# Answer
# CJam, 11 bytes

```
ri_mf,\mF,-

```

Try it online!

**Explanation**

```
ri_         Get an integer from input and duplicate it
   mf,      Get the number of prime factors (with repetition)
      \     Swap top 2 elements on the stack
       mF,  Get the number of prime factors (with exponents)
          - Subtract

```
> 0 votes

# Answer
# APL(NARS) 35 chars, 70 bytes

```
{⍵=1:0⋄k-⍨+/+/¨{w=⍵⊃v}¨⍳k←≢v←∪w←π⍵}

```

the function π find the factorization in prime of its argument; there is few to say it seems clear, but for me does more operations (from factorization) than the minimum...the range of count characters is out golfing languages because it seems too much count, but less than not golfing languages... test:

```
  f←{⍵=1:0⋄k-⍨+/+/¨{w=⍵⊃v}¨⍳k←≢v←∪w←π⍵}
  f¨1..15
0 0 0 1 0 0 0 2 1 0 0 1 0 0 0

```
> 0 votes

# Answer
# Arturo, 47 bytes

```
$=>[k:tally factors.prime&(∑values k)-size k]

```

Try it!
> 0 votes

# Answer
# Vyxal `s`, 3 bytes

```
ǐ¯†

```

Try it Online!

Ports 05AB1E. Vyncode makes the byte count worse.

## Explained

```
ǐ¯†
ǐ    # Prime factors with duplicates
 ¯   # deltas
  †  # vectorised negation
# summed by the s flag

```
> 0 votes

---
Tags: code-golf, sequence, number-theory, primes
---


title: 2048-like array shift

text:
# Question
Title: 2048-like array shift
Assume we want to shift an array like it is done in the 2048 game: if we have two equal consecutive elements in array, merge them into twice the value element. Shift must return a new array, where every pair of consecutive equal elements is replaced with their sum, and pairs should not intersect. Shifting is performed only once, so we don't need to merge resulting values again. Notice that if we have 3 consecutive equal elements, we have to sum rightmost ones, so for example, `[2, 2, 2]` should become `[2, 4]`, not `[4, 2]`.

The task is to write shortest function which takes an array and returns a shifted array.

You may assume that all integers will be strictly positive.

Examples:

```
[] -> []
[2, 2, 4, 4] -> [4, 8]
[2, 2, 2, 4, 4, 8] -> [2, 4, 8, 8]
[2, 2, 2, 2] -> [4, 4]
[4, 4, 2, 8, 8, 2] -> [8, 2, 16, 2]
[1024, 1024, 512, 512, 256, 256] -> [2048, 1024, 512]
[3, 3, 3, 1, 1, 7, 5, 5, 5, 5] -> [3, 6, 2, 7, 10, 10]

```

I am also very interested in solution using reduce :)

# Answer
# Jelly, ~~10 9~~ 8 bytes

```
Œg+2/€UF

```

**TryItOnline** or **run all test cases**

### How?

```
Œg+2/€UF - Main link: a                 e.g. [2,2,2,4,4,8]
Œg       - group runs of equal elements      [[2,2,2],[4,4],[8]]
   2/€   - pairwise reduce for each with
  +      -     addition                      [[4,2],[8],[8]]
      U  - reverse (vectorises)              [[2,4],[8],[8]]
       F - flatten list                      [2,4,8,8]

```
> 24 votes

# Answer
## Haskell, ~~47~~ ~~57~~ 50 bytes

```
e#l|a:b<-l,e==a= -2*a:b|1<2=e:l
map abs.foldr(#)[]

```

Uses `reduce` (or `fold` as it is called in Haskell, here a right-fold `foldr`). Usage example: `map abs.foldr(#)[] $ [2,2,2,4,4,8]` -\> `[2,4,8,8]`.

Edit: +10 bytes to make it work for unsorted arrays, too. Merged numbers are inserted as negative values to prevent a second merge. They are corrected by a final `map abs`.
> 19 votes

# Answer
# Brain-Flak, 158 96

```
{({}<>)<>}<>{(({}<>)<><(({})<<>({}<>)>)>)({}[{}]<(())>){((<{}{}>))}{}{{}(<({}{})>)}{}({}<>)<>}<>

```

Try it online!

**Explanation:**

1 Reverse the list (moving everything to the other stack, but that doesn't matter)

```
{({}<>)<>}<>
{        }   #keep moving numbers until you hit the 0s from an empty stack
 ({}<>)      #pop a number and push it on the other stack
       <>    #go back to the original stack
          <> #after everything has moved, switch stacks

```

2 Do steps 3-6 until there is nothing left on this stack:

```
{                                                                                }

```

3 Duplicate the top two elements (2 3 -\> 2 3 2 3)

```
(({}<>)<><(({})<<>({}<>)>)>)

(({}<>)<>                   #put the top number on the other stack and back on the very top
         <(({})             #put the next number on top after:
               <<>({}<>)>   #copying the original top number back to the first stack
                         )>)

```

4 Put a 1 on top if the top two are equal, a 0 otherwise (from the wiki)

```
({}[{}]<(())>){((<{}{}>))}{}

```

5 If the top two were equal (non-zero on the top) add the next two and push the result

```
{{}(<({}{})>)}{}
{            }   #skip this if there is a 0 on top
 {}              #pop the 1
   (<      >)    #push a 0 after:
     ({}{})      #pop 2 numbers, add them together and push them back on
              {} #pop off the 0

```

6 Move the top element to the other stack

```
({}<>)<>

```

7 Switch to the other stack and print implicitly

```
<>

```
> 14 votes

# Answer
# PHP, 116 Bytes

```
<?$r=[];for($c=count($a=$_GET[a]);$c-=$x;)array_unshift($r,(1+($x=$a[--$c]==$a[$c-1]))*$a[$c]);echo json_encode($r);

```

or

```
<?$r=[];for($c=count($a=$_GET[a]);$c--;)$r[]=$a[$c]==$a[$c-1]?2*$a[$c--]:$a[$c];echo json_encode(array_reverse($r));

```

-4 Bytes if the output can be an array `print_r` instead of 'json\_encode\`

176 Bytes to solve this with a Regex

```
echo preg_replace_callback("#(\d+)(,\\1)+#",function($m){if(($c=substr_count($m[0],$m[1]))%2)$r=$m[1];$r.=str_repeat(",".$m[1]*2,$c/2);return trim($r,",");},join(",",$_GET[a]));

```
> 9 votes

# Answer
# GNU sed, 41 38 37

Includes +1 for -r
-3 Thanks to Digital Trauma
-1 Thanks to seshoumara

```
:
s,(.*)(1+) \2\b,\1!\2\2!,
t
y,!, ,

```

Input and output are space separated strings in unary (based on this consensus).

Try it online!
> 9 votes

# Answer
## Python, 61 bytes

```
def f(l):b=l[-2:-1]==l[-1:];return l and f(l[:~b])+[l[-1]<<b]

```

The Boolean `b` checks whether the last two elements should collapse by checking that they are equal in a way that's safe for lists of length 1 or 0. The last element if then appended with a multiplier of `1` for equal or `2` for unequal. It's appended to the recursive result on the list with that many elements chopped off the end. Thanks to Dennis for 1 byte!
> 9 votes

# Answer
# Retina, 32

```
\d+
$*
r`\b\1 (1+)\b
$1$1
1+
$.&

```

`r` on line 3 activates right-to-left regex matching. And this means that the `\1` reference needs to come before the `(1+)` capturing group that it references.

Try it online.
> 8 votes

# Answer
# Perl, 41 bytes

Includes +1 for `-p`

Give input sequence on STDIN:

```
shift2048.pl <<< "2 2 2 4 4 8 2"

```

`shift2048.pl`:

```
#!/usr/bin/perl -p
s/.*\K\b(\d+) \1\b/2*$1.A/e&&redo;y/A//d

```
> 8 votes

# Answer
# JavaScript (ES6), 68 bytes

```
f=a=>a.reduceRight((p,c)=>(t=p[0],p.splice(0,c==t,c==t?c+t:c),p),[])

console.log([
  [],
  [2, 2, 4, 4],
  [2, 2, 2, 4, 4, 8],
  [2, 2, 2, 2],
  [4, 4, 2, 8, 8, 2],
  [1024, 1024, 512, 512, 256, 256],
  [3, 3, 3, 1, 1, 7, 5, 5, 5, 5],
].map(f))
```
> 8 votes

# Answer
## Perl, 43 + 1 (`-p`) = 44 bytes

Ton Hospel came up with 41 bytes answer, check it out!

*-4 thanks to @Ton Hospel!*

**Edit** : added `\b`, as without it it was failing on input like `24 4` on which the output would have been `28`.

```
$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge

```

Run with `-p` flag :

```
perl -pe '$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge' <<< "2 2 2 4 4"

```

I don't see another way than using `reverse` twice to right-fold (as just `s/(\d+) \1/$1*2/ge` would left-fold, i.e `2 2 2` would become `4 2` instead of `2 4`). So 14 bytes lost thanks to `reverse`... Still I think there must be another (better) way (it's perl after all!), let me know if you find it!
> 7 votes

# Answer
# JavaScript (ES6),  ~~68...64~~  58 bytes

```
a=>(g=p=>(x=a.pop())|p?p?[...g(p^x?x:!(p*=2)),p]:g(x):a)()

```

Try it online!

### Commented

```
a => (                  // a[] = input array
  g = p =>              // g is a recursive function taking p = previous value
    (x = a.pop())       //   extract the last entry x from a[]
    | p ?               //   if either x or p is a positive integer:
      p ?               //     if p is a positive integer:
        [               //       update the output:
          ...g(         //         do a recursive call:
            p ^ x ?     //           if p is not equal to x:
              x         //             set new_p = x
            :           //           else:
              !(p *= 2) //             double p and set new_p = false
          ),            //         end of recursive call
          p             //         append p
        ]               //       end of output update
      :                 //     else:
        g(x)            //       do a simple recursive call with new_p = x
    :                   //   else:
      a                 //     stop recursion and return a[], which is guaranteed
                        //     to be an empty array at this point
)()                     // initial call to g with p undefined

```
> 7 votes

# Answer
# Perl 5.10, ~~61~~ 50 bytes (~~49~~ \+ 1 for flag)

Thanks to Ton Hospel for saving 11 bytes!

Regex-free solution, with `-a` flag:

```
@a=($F[-1]-$b?$b:2*pop@F,@a)while$b=pop@F;say"@a"

```

Try here!
> 7 votes

# Answer
# 05AB1E, 26 bytes

```
D¥__X¸«DgL*ê¥X¸«£vy2ôO})í˜

```

Try it online!

**Generalized steps**

1. Reduce by subtraction to find where consecutive elements differ
2. Reduce by subtraction over the indices of those places to find the length of consecutive elements
3. Split input into chunks of those lengths
4. Split chunks into pairs
5. Sum each pair
6. Reverse each summed chunk
7. Flatten to 1-dimensional list
> 6 votes

# Answer
# Mathematica, 53 bytes

```
Join@@(Reverse[Plus@@@#~Partition~UpTo@2]&/@Split@#)&

```

# Explanation

```
Split@#

```

Split the input into sublists consisting of runs of identical elements. i.e. `{2, 2, 2, 4, 8, 8}` becomes `{{2, 2, 2}, {4}, {8, 8}}`.

```
#~Partition~UpTo@2

```

Partition each of the sublist into partitions length at most 2. i.e. `{{2, 2, 2}, {4}, {8, 8}}` becomes `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}`.

```
Plus@@@

```

Total each partition. i.e. `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}` becomes `{{4, 2}, {4}, {16}}`.

```
Reverse

```

Reverse the results because Mathematica's `Partition` command goes from left to right, but we want the partitions to be in other direction. i.e. `{{4, 2}, {4}, {16}}` becomes `{{2, 4}, {4}, {16}}`.

```
Join@@

```

Flatten the result. i.e. `{{2, 4}, {4}, {16}}` becomes `{2, 4, 4, 16}`.
> 5 votes

# Answer
# Haskell, 56 bytes

```
g(a:b:r)|a==b=a+b:g r|l<-b:r=a:g l
g x=x
r=reverse
r.g.r

```
> 5 votes

# Answer
## Java 7, 133 bytes

```
Object f(java.util.ArrayList<Long>a){for(int i=a.size();i-->1;)if(a.get(i)==a.get(i-1)){a.remove(i--);a.set(i,a.get(i)*2);}return a;}

```

Input is an ArrayList, and it just loops backwards, removing and doubling where necessary.

```
Object f(java.util.ArrayList<Long>a){
    for(int i=a.size();i-->1;)
        if(a.get(i)==a.get(i-1)){
            a.remove(i--);
            a.set(i,a.get(i)*2);
        }
    return a;
}

```
> 5 votes

# Answer
# Perl, 37 bytes

Includes +4 for `-0n`

Run with the input as separate lines on STDIN:

```
perl -M5.010 shift2048.pl
2
2
2
4
4
8
2
^D

```

shift2048.pl:

```
#!/usr/bin/perl -0n
s/\b(\d+
)(\1|)$//&&do$0|say$1+$2

```
> 4 votes

# Answer
# PHP, ~~86 100 99~~ 94 bytes

```
for($r=[];$v=+($p=array_pop)($a=&$argv);)array_unshift($r,end($a)-$v?$v:2*$p($a));print_r($r);

```

requires PHP 7.0; takes values from command line arguments.

Run with `-nr` or try it online.
> 4 votes

# Answer
# Julia 205 bytes

```
t(x)=Val{x}
s(x)=t(x)()
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))
g()=[]
g{a}(::t(a))=[a]
g{a}(::t(a),B...)=[a;g(B...)]
g{a}(::t(a),::t(a),B...)=[2a;g(B...)]
K(A)=g(s.(A)...)
H(A)=(K^s(length(A)))(A)

```

Function to be called is `H`

eg `H([1,2,2,4,8,2,])`

This is in no way the shortest way do this in julia. But it is so cool, that I wanted to share it anyway.

* `t(a)` is a value-type, representing the value (a).
* `s(a)` is an instance of that value type
* `g` is a function that dispatches on the difference values (using the value types) and numbers of its parameters. And that is cool
* `K` just wraps `g` so that

Extra cool part:

```
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))

```

This defines the `^` operator to apply to functions. So that `K^s(2)(X)` is same as `K(K(X))` so `H` is just calling `K` on `K` a bunch of times -- enough times to certainly collapse any nested case

This can be done much much shorter, but this way is just so fun.
> 3 votes

# Answer
## PowerShell v2+, 81 bytes

```
param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count..0]

```

Takes input as an explicit array `$n`, reverses it `$n[$n.count..0]`, `-join`s the elements together with a comma, then regex `-replace`s a matching digit pair with the first element, a `*2`, and surrounded in parens. Pipes that result (which for input `@(2,2,4,4)` will look like `(4*2),(2*2)`) over to `iex` (short for `Invoke-Expression` and similar to `eval`), which converts the multiplication into actual numbers. Stores the resulting array into `$b`, encapsulates that in parens to place it on the pipeline, then reverses `$b` with `[$b.count..0]`. Leaves the resulting elements on the pipeline, and output is implicit.

---

### Test Cases

***NB--*** In PowerShell, the concept of "returning" an empty array is meaningless -- it's converted to `$null` as soon as it leaves scope -- and so it is the equivalent of returning nothing, which is what is done here in the first example (after some wickedly verbose errors). Additionally, the output here is space-separated, as that's the default separator for stringified arrays.

```
PS C:\Tools\Scripts\golfing> @(),@(2,2,4,4),@(2,2,2,4,4,8),@(2,2,2,2),@(4,4,2,8,8,2),@(1024,1024,512,512,256,256),@(3,3,3,1,1,7,5,5,5,5)|%{"$_ --> "+(.\2048-like-array-shift.ps1 $_)}
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:67
+   param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+                                                                   ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

Cannot index into a null array.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:13
+   param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

 -->
2 2 4 4 --> 4 8
2 2 2 4 4 8 --> 2 4 8 8
2 2 2 2 --> 4 4
4 4 2 8 8 2 --> 8 2 16 2
1024 1024 512 512 256 256 --> 2048 1024 512
3 3 3 1 1 7 5 5 5 5 --> 3 6 2 7 10 10

```
> 3 votes

# Answer
# Javascript - 103 bytes

```
v=a=>{l=a.length-1;for(i=0;i<l;i++)a[l-i]==a[l-1-i]?(a[l-i-1]=a[l-i]*2,a.splice(l-i,1)):a=a;return a}

```
> 3 votes

# Answer
# Brain-Flak, 60 bytes

```
{({}<>)<>}<>{(({}<>)<>[({})]){((<{}>))}{}{({}<>{})(<>)}{}}<>

```

Try it online!

### Explanation:

```
{({}<>)<>}<>   Reverse stack

{   While input exists
  (
    ({}<>)   Push copy of last element to the other stack
    <>[({})] And subtract a copy of the next element
  )   Push the difference
  {   If the difference is not 0
    ((<{}>)) Push two zeroes
  }{}  Pop a zero
  {   If the next element is not zero, i.e the identical element
    ({}<>{})  Add the element to the copy of the previous element
    (<>)      Push a zero
  }{}    Pop the zero
}<>  End loop and switch to output stack

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 20 bytes

```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽

```

Try it online!

Fully tacit version of the previous solution, thanks to Adám.

### How it works

```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽  ⍝ Right argument: V, vector to reduce by 2048 rules
                   ⌽  ⍝ Reverse V to get RV
                ,\∘   ⍝ Prefixes of RV
         ⌽(  =)¨      ⍝ For each prefix, test if each element equals last element
           ⊥⍨         ⍝   and count trailing ones
                      ⍝   (one-based index of each item within runs)
       2|             ⍝ Modulo 2
    ⌽⊂⍨               ⍝ Partition RV at ones of the above
 1⊥¨                  ⍝ Sum of each chunk
⌽                     ⍝ Reverse back

```

---

# APL (Dyalog Unicode), 26 bytes

```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕

```

Try it online!

A full program. Link is to function version for easier testing.

### How it works

```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕
                         ⎕  ⍝ Take input
                        ⌽   ⍝ Reverse
    {                  }    ⍝ Apply the anonymous function...
                    ,\⍵     ⍝   Prefixes
          {       }¨        ⍝   For each prefix,
             ⍵=⊃⌽⍵          ⍝     Evaluate if each element is equal to last
           ⊥⍨               ⍝     and count trailing ones
                            ⍝     (one-based index of each item within runs)
        2|                  ⍝   Take modulo 2
     ⍵⊂⍨                    ⍝   Partition the input array at 1's of the above
 +/¨                        ⍝ Sum each group
⌽                           ⍝ Reverse back

```
> 3 votes

# Answer
# Python 2, 94 bytes

```
def f(a,r=[]):
 while a:
    if len(a)>1and a[-1]==a[-2]:a.pop();a[-1]*=2
    r=[a.pop()]+r
 print r

```

**Try it online**
> 2 votes

# Answer
# Julia 0.6, ~~73~~ 82 Bytes

```
f(l)=l==[]?[]:foldr((x,y)->y[]==x?vcat(2x,y[2:end]):vcat(x,y),[l[end]],l[1:end-1])

```

Try it online!

Use right fold to build list from back to front (one could also use fold left and reverse the list at the beginning and end).

If the head of the current list is not equal to the next element to prepend, then just prepend it.

Else remove the head of the list (sounds kind of cruel) and prepend the element times 2.

*Example*

```
f([3,3,3,1,1,7,5,5,5,5])
returns a new list:
[3,6,2,7,10,10]

```
> 2 votes

# Answer
## Racket 166 bytes

```
(λ(l)(let g((l(reverse l))(o '()))(cond[(null? l)o][(=(length l)1)(cons(car l)o)]
[(=(car l)(second l))(g(drop l 2)(cons(* 2(car l))o))][(g(cdr l)(cons(car l)o))])))

```

Ungolfed:

```
(define f
  (λ (lst)
    (let loop ((lst (reverse lst))
               (nl '()))
      (cond                            ; conditions:
        [(null? lst)                   ; original list empty, return new list;
               nl]
        [(= (length lst) 1)            ; single item left, add it to new list
              (cons (first lst) nl)]
        [(= (first lst) (second lst))  ; first & second items equal, add double to new list
              (loop (drop lst 2)
                    (cons (* 2 (first lst)) nl))]
        [else                          ; else just move first item to new list
              (loop (drop lst 1)
                    (cons (first lst) nl))]
        ))))

```

Testing:

```
(f '[])
(f '[2 2 4 4])
(f '[2 2 2 4 4 8])
(f '[2 2 2 2])
(f '[4 4 2 8 8 2])
(f '[1024 1024 512 512 256 256])
(f '[3 3 3 1 1 7 5 5 5 5])
(f '[3 3 3 1 1 7 5 5 5 5 5])

```

Output:

```
'()
'(4 8)
'(2 4 8 8)
'(4 4)
'(8 2 16 2)
'(2048 1024 512)
'(3 6 2 7 10 10)
'(3 6 2 7 5 10 10)

```
> 2 votes

# Answer
# Mathematica, 51 bytes

```
Abs[#//.{Longest@a___,x_/;x>0,x_,b___}:>{a,-2x,b}]&

```

---

`{Longest@a___,x_/;x>0,x_,b___}` matches a list containing two consecutive identical positive numbers and transform these two numbers into `-2x`. `Longest` forces the matches to happen as late as possible.

The process is illustrated step by step:

```
   {3, 3, 3, 1, 1, 7, 5, 5, 5, 5}
-> {3, 3, 3, 1, 1, 7, 5, 5, -10}
-> {3, 3, 3, 1, 1, 7, -10, -10}
-> {3, 3, 3, -2, 7, -10, -10}
-> {3, -6, -2, 7, -10, -10}
-> {3, 6, 2, 7, 10, 10}

```
> 1 votes

# Answer
# Japt, 12 bytes

```
ò¦ ®ò2n)mxÃc

```

Try it online!

### Unpacked & How it works

```
Uò!= mZ{Zò2n)mx} c

Uò!=    Partition the input array where two adjacent values are different
        i.e. Split into arrays of equal values
mZ{     Map the following function...
Zò2n)     Split into arrays of length 2, counting from the end
          e.g. [2,2,2,2,2] => [[2], [2,2], [2,2]]
mx        Map `Array.sum` over it
}
c       Flatten the result

```

Got some idea from Jonathan Allan's Jelly solution.
> 1 votes

# Answer
# Common Lisp, 143 bytes

```
(defun e(l)(if(<(length l)1)'()(if(eq(car l)(cadr l))(cons(*(car l)2)(e(cddr l)))(cons(car l)(e(cdr l))))))
(defun f(l)(reverse(e(reverse l))))

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~100~~ ~~73~~ 71 bytes

Thanks to @jo-king -27 bytes! and @jakque -2 bytes

```
n=lambda l:l[1:]and[*n(l[:~(l[-1]==l[-2])]),l[-1]*-~(l[-1]==l[-2])]or l

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 34 bytesSBCS

Anonymous prefix lambda.

```
{∊((⊃⍴⍨2|≢),+⍨⍴⍨∘⌊2÷⍨≢)¨⍵⊂⍨2≠/0,⍵}

```

Try it online!

`{``}` dfn;  is right argument

`0,⍵` prepend a zero to the argument

`2≠/` pairwise inequality mask

`⍵⊂⍨` use that to partition (true means begin new partition here) the argument

`(` apply the following tacit function to each run of equal numbers:

the length of the run

`2÷⍨` let 2 divide that

floor that

then

`⍴⍨` use it to **r**eshape…

`+⍨` the doubled (lit. addition selfie) run

`(``),` append that to the following:

the length of the run

`2|` division remainder when divided by two (1 for odd length runs, 0 for even length runs)

`⊃⍴⍨` use that to reshape the first element of the run

**e**nlist (flatten)
> 1 votes

# Answer
# 05AB1E (legacy), ~~8~~ 7 bytes

```
γ2δôOí˜

```

-1 byte thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
γ        # Split the (implicit) input into chunks of equal adjacent values
         #  i.e. [4,4,2,8,8,8,2] → [[4,4],[2],[8,8,8],[2]]
  δ      # Map each to:
 2 ô     #  Split it into parts of size 2
         #   → [[[4,4]],[[2]],[[8,8],[8]],[[2]]]
    O    # Take the sum of each
         #  → [[8],[2],[16,8],[2]]
     í   # Reverse each
         #  → [[8],[2],[8,16],[2]]
      ˜  # Flatten everything
         #  → [8,2,8,16,2]
         # (after which the resulting list is output implicitly)

```
> 1 votes

# Answer
# Nekomata, 7 bytes

```
ĉ~ĭ+↔aj

```

Attempt This Online!

A port of @The Thonnu's Thunno 2 answer.

```
ĉ~ĭ+↔aj
ĉ           Split the input into runs of identical items
 ~   a      For each run:
  ĭ             Deinterleave
   +            Add
    ↔           Reverse
      j     Concatenate

```
> 1 votes

# Answer
## Java 8, ~~130~~ 114 bytes

**Edit:**

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

Snipet:

```
s->{int j=0,i=s.length,l[]=new int[i];for(;--i>-1;[j++]=s[i]==s[i-1]?s[i--]*2:s[i]);return Collection.reverse(l);}

```

Code:

```
public static int[] shift(int[]a){
  List<int> out = new ArrayList<>();
  for(int i = s.length-1; i>-1;i--){
    if(s[i]==s[i-1]){
      out.add(s[i]*2);
      i--;
    }else{
      out.add(s[i]);
    }
  }
  return Arrays.reverse(out.toArray());
}

```
> 0 votes

# Answer
# Vim, 28 bytes

`G@='?\v(\d+)\n\1<C-@>DJ@"<C-A>-@=<C-@>'<CR>`

A macro that regex searches backward for matching consecutive numbers, and adds them together.

**The input array needs to be one number per line.** This format saves me strokes, which is nice, but the real reason is to work around overlapping regex matches. Given the string `222`, if you `/22` you'll match only the first pair, not the overlapping second pair. The overlap rules are different when the two pairs start on different lines. In this challenge `[2, 2, 2]` becomes `[2, 4]`, so matching the overlapping pair is critical.

**NOTE:** The challenge asked for only a single pass. For that reason, you need to have `:set nowrapscan`. With `:set wrapscan` I could make a version that finishes the job on multiple passes, though this solution as written won't always do that.

* `<C-@>`: Normally, in a command line, to type a literal `<CR>` without running the command you'd have to escape it with `<C-V>`. But you can type `<C-@>` unescaped and it will be treated as a `<C-J>`/`<NL>`, which will be like `<CR>` when you run the macro but not when you're typing. Try reading `:help NL-used-for-Nul`.
* `@=`: I can't use a recorded macro easily this time because there's a possibility the input might have no matching pairs. If that happens while running a macro, the unsuccessful search will fail the macro. But if it happens during the (implicit first) recording pass, the rest of the normal mode commands will run, damaging the file. The downside of `@=` is I lose a byte on the recursive call; sometimes you can use `@@` as a recursive call, but that would run `@"` from 4 bytes earlier in this case.
* `DJ@"<C-A>-`: `DJ` deletes the line and puts the number (no newline) in a register, so I can run it as a macro for a number argument to `<C-A>`. I have to `-` afterward so I don't get a second match in cases like `[4, 2, 2]`.
> 0 votes

# Answer
## Perl6, 92 bytes

```
{my @b;loop ($_=@^a-1;$_>=0;--$_) {@b.unshift($_&&@a[$_]==@a[$_-1]??2*@a[$_--]!!@a[$_])};@b}

```
> 0 votes

# Answer
# Prolog (SWI), ~~97~~ 87 bytes

```
[N,N|T]+[O|Q]:-O is N*2,T+Q.
[N|T]+[N|Q]:-T+Q.
R+R.
L-R:-reverse(L,M),M+Q,reverse(Q,R).

```

Try it online!
> 0 votes

# Answer
# Ruby, 55 bytes

```
->a{c=[];c=[(b=a.pop)==a[-1]?a.pop*2:b]+c while a[0];c}

```

Try it online!

So long and still no Ruby answer? It can't be.

More golfing will follow.
> 0 votes

# Answer
# C (GCC), 87 bytes

I'm not very familiar with the allowed I/O methods for C, but I think this is valid. The function takes an input array `a` (`int *`) and length `l` and two empty parameters `r` and `w` (`int`). The output is stored to the right portion of the input array, and the new length is returned.

```
f(a,l,r,w)int*a;{for(r=w=l;r--;)a[--w]=r<1|a[r]-a[r-1]?a[r]:a[r--]*2;return!!~l*~w-~l;}

```

Try It Online

The program may read at index -1 in the input array, which seems to work fine in my test program. Valgrind reports this access in some cases, but I was unable to get this to crash the program with global, automatic, or `malloc`ed input arrays on my system.

## Acknowledgments
> 0 votes

# Answer
# Powershell, ~~73~~ 71 bytes

```
for($r=@();$z=$args[--$i]){$i-=$e=$z-eq$args[$i-1]
$r=,($z+$z*$e)+$r}$r

```

Less golfed test script:

```
$f = {

$r=@()                      # result
for(;$z=$args[--$i]){       # all elements from end to start
    $e=$z-eq$args[$i-1]     # current is $equal to previous
    $i-=$e                  # shift if need
    $r=,($z+$z*$e)+$r       # insert to start
}
$r                          # output result

}

@(
    ,( @()  ,  @() )
    ,( (2, 2, 4, 4)  , (4, 8) )
    ,( (2, 2, 2, 4, 4, 8)  , (2, 4, 8, 8) )
    ,( (2, 2, 2, 2)  , (4, 4) )
    ,( (4, 4, 2, 8, 8, 2)  , (8, 2, 16, 2) )
    ,( (1024, 1024, 512, 512, 256, 256)  , (2048, 1024, 512) )
    ,( (3, 3, 3, 1, 1, 7, 5, 5, 5, 5)  , (3, 6, 2, 7, 10, 10) )
) | % {
    $arr,$expected = $_
    $result = &$f @arr     # splatting
    "$("$result"-eq"$expected"): $result"
}

```

Output:

```
True:
True: 4 8
True: 2 4 8 8
True: 4 4
True: 8 2 16 2
True: 2048 1024 512
True: 3 6 2 7 10 10

```
> 0 votes

# Answer
# Pushy, 18 bytes

```
$L1=?v;2d=?+;v;O@_

```

**Try it online!**

```
$                     \ While there are items left on input stack:
 L1=?                 \  if len(input) == 1:
     v;               \    move the final remaining item to output stack
                      \  else:
       2d             \    copy the last two items
         =?           \    if equal:
           +;         \      add together
             v;       \    move the last item on stack to output stack
               O@_    \ Print the output stack (reversed)

```
> 0 votes

# Answer
# Lua 5.3, ~~117~~ 113 bytes

```
function f(t)i,o=#t,{}while i>0 do v=t[i]if v==t[i-1]then v=v*2i=i-1 end i=i-1table.insert(o,1,v)end return o end

```

Try it online!

I think Lua 5.1 would require an extra byte because a number has to be separated from an identifier: `v=v*2i=i-1``v=v*2 i=i-1`.
> 0 votes

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

```
x=>{for(int i=x.Count-1;i>0;)if(x[i--]==x[i]){x.RemoveAt(i);x[i--]*=2;}}

```

Try it online!

This function outputs by modifying an argument.

Credit to @ASCIIOnly for suggesting that I *not* create a new list. That suggestion led me to discover the above referenced rule. Total savings of 22 bytes without creating a new list and by removing the return statement :)

Less golfed...

```
// x is an input List
x=>{
  // iterate from back to front
  for(int i=x.Count-1;i>0;)
    // check for consecutive elements
    if(x[i--]==x[i]){
      // remove the first occurrence
      x.RemoveAt(i);
      // double the second occurrence
      // which has been shifted
      x[i--]*=2;
    }
}

```
> 0 votes

# Answer
# F# (.NET Core), 87 bytes

```
fun x->(List.foldBack(fun e (h::t)->if h=e then 0::e*2::t.Tail else e::e::t)x [0]).Tail

```

Try it online!

Uses the `List.foldBack` function to process the input from back to front. The head of the working list contains an element that can be merged, or a `0` to indicate the previous element cannot be merged
> 0 votes

# Answer
# Husk, 8 bytes

```
ṁȯ↔mΣC2g

```

Try it online!

is a lifesaver here.
> 0 votes

# Answer
# Julia 1.0, 69 bytes

```
x\y=x!==y[1] ? Int[x;y] : [2.0x;[y;][2:end]]
!l=l>[] ? foldr(\,l) : l

```

Try it online!

when 2 numbers are merged, they are turned into a float, so that it won't be `===` to the next number, which is an integer. When there is no merge, the numbers are converted back to integers to re-allow merging numbers

based on this answer

# Julia 0.6, 61 bytes

```
x\y=x!==y[]?Int[x;y]:[2.0x;[y;][2:end]]
!l=l!=[]?foldr(\,l):l

```

Try it online!
> 0 votes

# Answer
# Java (JDK), ~~114~~ 112 bytes

```
n->{List l=new Stack();for(int i=n.length;i-->1;)if(n[i]>0)l.add(n[i]==n[i-1]?n[i]*2+(n[i-1]=0):n[i]);return l;}

```

Try it online!

Returns the list in reverse. -2 Thanks to celingcat.
> 0 votes

# Answer
# Japt, 9 bytes

```
òÎc_ò Ômx

```

Try it or run all test cases

```
òÎc_ò Ômx     :Implicit input of array
ò             :Partition between elements where
 Î            :  The sign of their difference is truthy (not 0)
  c           :Map then flatten
   _          :By passing each array through the following function
    ò         :  Partitions of length 2
      Ô       :  Reverse
       m      :  Map
        x     :    Reduce by addition

```
> 0 votes

# Answer
# Arturo, 57 bytes

```
$=>[chunk&=>[&]|map=>[map&++0[x y]->x+y|reverse]|flatten]

```

Try it!

```
$=>[                     ; a function where input is assigned to &
    chunk&=>[&]          ; split input into lists of equal contiguous elements
    |map=>[              ; then map each list to...
        map              ; map over...
        &++0             ; ...input list with 0 appended
        [x y]->          ; in pairs; assign elements to x and y
            x+y          ; add the pair
        |reverse         ; then reverse the list
    ]                    ; end map
    |flatten             ; then flatten the result
]                        ; end function

```
> 0 votes

# Answer
# Thunno 2 `S`, 6 bytes

```
ġı2ẇʂr

```

Attempt This Online!

Inspired by Jonathan Allan's Jelly answer.

#### Explanation

```
ġı2ẇʂr  # Implicit input              [2, 2, 2, 4, 4, 8]
ġ       # Group consecutive items     [[2, 2, 2], [4, 4], [8]]
 ı      # Map:                        [2, 2, 2]       [4, 4]     [8]
  2ẇ    #  Split into pairs           [[2, 2], [2]]   [[4, 4]]   [[8]]
    ʂ   #  Sum each inner list        [4, 2]          [8]        [8]
     r  #  Reverse                    [2, 4]          [8]        [8]
        # End map                     [[2, 4], [8], [8]]
        # Implicit output, flattened  [2, 4, 8, 8]

```
> 0 votes

# Answer
# Vyxal `d`, 43 bitsv2, 5.375 bytes

```
Ġƛy+ṘC

```

Try it Online!

Outputs as characters representing each value, as in this meta consensus.

*-5 bits thanks to @alephalpha*

## Explained

```
Ġƛy+ṘC
Ġƛ      # To each consecutive group of values:
  y+    #   Uninterleave the group and add the two halves
    Ṙ   #   Reverse
     C  #   Convert to character
# The d flag flattens then sums the result

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```
> 0 votes

---
Tags: code-golf, array, sliding-puzzle
---