Make a "Ceeeeeeee" program

95

13

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 es. 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.

Esolanging Fruit

Posted 2016-11-19T19:18:53.747

Reputation: 13 542

27Kinda random, but +1 – TuxCrafting – 2016-11-19T19:28:10.313

25+1 for Meeeeeeeeegram – FlipTack – 2016-11-19T20:15:59.760

In the case that it returns an array, do each of the elements have to include a trailing newline? – Brad Gilbert b2gills – 2016-11-19T20:24:17.987

@BradGilbertb2gills No. – Esolanging Fruit – 2016-11-19T20:40:30.817

Reminded me of SOMA Transmission #8 (look up on YouTube). "It's the weight of the s-e-e-e-ea!" – Malcolm – 2016-11-21T16:23:31.753

4Meeeeeeeeeeeeem – Mathime – 2016-11-23T07:52:56.310

String encoding matters a lot for how difficult this is in some languages. Should be be able to handle utf8 in both the input character and the string? – Harald Korneliussen – 2016-12-02T08:30:38.800

Input: Return expression_that_is_so_long_that_you_cant_even_read_in_one_second, Output: *Reeeeeee* – Matthew Roh – 2017-04-18T11:19:35.850

@l4m2 The alphabet example I think answers your question but I'm not sure. The first character will never be pruned and every iteration should prune a character as shown by the "Ceee" example – Veskah – 2018-05-23T01:27:46.973

Answers

5

V, 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)

Non-competing version (11 bytes)

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

James

Posted 2016-11-19T19:18:53.747

Reputation: 54 537

@challenger5 Awesome! I'll check out an old version and verify that it works correctly. I might have to modify it slightly. I'll ping you once I've updated. – James – 2017-02-14T19:59:38.613

@Challenger5 I have edited the answer, and verified that this version worked when the challenge was posted. – James – 2017-02-14T23:27:28.943

How would I execute a bunch of Vim commands stored in a file on a Linux system? Would i cat filename | vim or would I do something else? – ckjbgames – 2017-02-15T00:43:11.087

31

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

James

Posted 2016-11-19T19:18:53.747

Reputation: 54 537

1I think you got a typo there where the input is given there is a k too much :) – geisterfurz007 – 2016-11-21T10:52:58.910

@geisterfurz007 I'm not sure if I get what you mean? – James – 2016-11-22T23:33:04.897

It says (...)comk In line 5 currently. – geisterfurz007 – 2016-11-22T23:37:41.207

There's no reason to use :t here. Normal Yp would save a byte. You'll have to switch to <C-R>- of course. Typical PPCG rules are frustrating, because for any reasonable test case, :t.|s with 99@: or even 999@: would be correct, but there's no good way to get an infinite repeat that way. You're forced to use less interesting strats. – udioica – 2016-11-29T21:55:04.210

22

MATL, 20 16 bytes

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

Try it online! Or verify test cases: 1, 2, 3, 4, 5.

Bonus

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

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

enter image description here

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

Luis Mendo

Posted 2016-11-19T19:18:53.747

Reputation: 87 464

3GIFS! gifs are cool! – Brain Guider – 2016-11-21T13:22:21.440

20

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]

dianne

Posted 2016-11-19T19:18:53.747

Reputation: 1 049

3Can you explain the code? – bli – 2016-11-22T11:52:30.063

1@bli Done! Hopefully this helps? – dianne – 2016-11-23T02:18:04.613

14

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.

Martin Ender

Posted 2016-11-19T19:18:53.747

Reputation: 184 808

10

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"

msh210

Posted 2016-11-19T19:18:53.747

Reputation: 3 094

You can just specify "no newline in the input" (which is how the second program works). If you badly need to remove newlines in the input, look into the -l option, which turns on an automatic newline handling mode in which print prints an additional newline (irrelevant here) and -p/-n input removes the newline (very relevant). Also, it's deprecated, but I think you can replace the ^I with a literal control-I for an extra byte of savings. Finally, I think s/.\K[^$^I]/redo/e would be one character shorter, although I'm not 100% sure that's a legal place to put a redo. – None – 2016-11-19T23:19:17.040

@ais523, thanks for the newline advice, but I guess I handled the issue well enough already. Re literal ^I, that's true for most of the control-letter variables, but not this one, IIRC. Re \K and putting redo in the replacement with /e, thanks! I'll test it when I have a chance to…. – msh210 – 2016-11-20T05:03:23.137

... and it doesn't work. @ais523 – msh210 – 2016-11-21T23:15:19.287

10

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.

DLosc

Posted 2016-11-19T19:18:53.747

Reputation: 21 213

8

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.

Brad Gilbert b2gills

Posted 2016-11-19T19:18:53.747

Reputation: 12 713

7

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

R. Kap

Posted 2016-11-19T19:18:53.747

Reputation: 4 730

I'm no python buff, but shouldn't this print only one line? – Conor O'Brien – 2016-11-19T20:08:27.560

@ConorO'Brien Yeah, I misread the post before. It's fixed now. – R. Kap – 2016-11-20T01:45:34.163

7

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.

Osable

Posted 2016-11-19T19:18:53.747

Reputation: 1 321

DˆćUΔD²KRнõ.;DXìˆ}¯¨» for 21, but that uses new commands. – Magic Octopus Urn – 2018-05-21T17:12:06.280

7

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:
















Guoyang Qin

Posted 2016-11-19T19:18:53.747

Reputation: 543

6

JavaScript (ES6), 74 bytes

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

Neil

Posted 2016-11-19T19:18:53.747

Reputation: 95 035

I think this produces incorrect output for f('test cases', 's') (ending with stss, rather than tsss). I think this is because replace removes the first occurance so it removes the first t rather than the second t in the fourth iteration of the map loop. – Lmis – 2016-11-21T14:00:53.730

@Lmis Thanks for pointing that out, I think I was able to fix one of my versions for "only" a 7 byte penalty. – Neil – 2016-11-21T19:19:34.220

5

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!

Ben Hili

Posted 2016-11-19T19:18:53.747

Reputation: 71

Welcome to the site! I am not an expert in Ruby golfing but it looks like you have extra whitespace. Particularly around the =s. For more comprehensive tips you can visit our tips page.

– Post Rock Garf Hunter – 2016-11-21T05:19:49.997

The easiest way to remove bytes is to eliminate excess whitespace, for example s=gets.chomp. I'm not sure if you can do this in Ruby but in some languages like Python you can combine multiple assignments into one statement, like a,b,c=0,1,2. – Esolanging Fruit – 2016-11-21T05:23:39.570

Hey thanks for the tip about whitespace read the ruby documentation and realised semicolons can replace them for ending statements :') as for making the s=gets.chop and c=gets.chop i cant do s,c=gets.chop or anything like that unfortunately theyre definitely the largest part of the code and I'd like to remove that lengthy statement.. – Ben Hili – 2016-11-21T05:26:25.053

You still have some extra spaces particularly before keywords (do,then and end), and around the fourth =. – Post Rock Garf Hunter – 2016-11-21T05:27:02.093

It looks like you are short changing yourself on the byte count. I only count 90 bytes myself. – Post Rock Garf Hunter – 2016-11-21T05:36:09.590

@WheatWizard trimmed it a bit more! The file size is being counted as 97 bytes in my file explorer... I guess I should've calculated them instead of taking explorers word on it thanks for pointing that out! – Ben Hili – 2016-11-21T05:37:28.827

then is not needed: Replace with ;, -4 bytes or so; c=gets[0], -1 byte – mhutter – 2016-11-21T14:05:40.277

Thanks for all your help guys down to about half what I started at! – Ben Hili – 2016-11-21T23:15:14.840

a,c=$*;s=""+a;i=1;p s;while s[i]do(s[i]!=c)?(s[i]="";p s):i+=1;end is 67 chars, extra trick with ternary and ""+a instead of Object#dup – jeroenvisser101 – 2016-11-22T13:45:36.503

Actually, it's 66 chars, I didn't count correctly – jeroenvisser101 – 2016-11-22T13:56:25.820

And -1 a,c=$*;s=""+a;i=1;p s;while s[i];(s[i]!=c)?(s[i]="";p s):i+=1;end, 65 bytes now – jeroenvisser101 – 2016-11-22T13:59:19.107

And -3 a,c=$*;p s=""+a;i=1;while d=s[i];(d!=c)?(s[i]="";p s):i+=1;end is 62 bytes – jeroenvisser101 – 2016-11-22T14:20:22.217

@jeroenvisser101 wow awesome job I love the s=""+a; trick very clever! – Ben Hili – 2016-11-22T22:00:41.610

4

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.

Bobby Sacamano

Posted 2016-11-19T19:18:53.747

Reputation: 149

3

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;.

Titus

Posted 2016-11-19T19:18:53.747

Reputation: 13 814

1$argv[1]."\n" can be written as "$argv[1]\n" – Ismael Miguel – 2016-11-20T02:14:03.687

1As $b gets a newline added to it it will always by truthy as long as it has length >= 1. As such the ""< is unnecessary. – user59178 – 2016-11-21T12:03:04.407

You can save another byte by using a ternary in the substr() rather than assigning $b. – user59178 – 2016-11-21T14:33:15.203

@user59178 I didn´t really catch you there: I need the substr result for both the condition and the print; so I should assign it somewhere. But You inspired me. – Titus – 2016-11-21T15:10:55.870

I meant for(;$b=substr($b?:".$argv[1]\n",1);) but what you have now even better. – user59178 – 2016-11-21T17:48:33.193

3

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

ngn

Posted 2016-11-19T19:18:53.747

Reputation: 11 449

3

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.

LegionMammal978

Posted 2016-11-19T19:18:53.747

Reputation: 15 731

I am definitely going to start using FixedPointList. – ngenisis – 2016-12-01T20:37:24.967

3

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.

Oliver Ni

Posted 2016-11-19T19:18:53.747

Reputation: 9 650

3

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

Kevin Cruijssen

Posted 2016-11-19T19:18:53.747

Reputation: 67 575

Wouldn't it be much shorter to not bother with a char[], and just use s.charAt()? – dpa97 – 2016-11-21T17:12:57.503

@dpa97 Ah, you're completely right. I used a foreach loop at first, but changed it to a regular for-loop. Forgot to remove the char-array. Thanks. – Kevin Cruijssen – 2016-11-21T17:52:15.383

2

JavaScript (ES6), 64 69

Returning a single string with newlines

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

F=
s=>c=>[...s].map((x,i,z)=>i&&x!=c&&(z[i]='',s+=`
`+z.join``))&&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>

edc65

Posted 2016-11-19T19:18:53.747

Reputation: 31 086

Slightly odd in that it doesn't take two arguments but one argument and then returns another function where you need to give the second argument. I'm not sure this was the expected behaviour. – MT0 – 2016-11-21T15:51:31.457

@MT0 I's odd but it's accepted for a function with 2 arguments, as it saves 1 byte. I'll give you a reference when I find one. Here it is http://meta.codegolf.stackexchange.com/a/8427/21348

– edc65 – 2016-11-21T16:18:24.363

Great technique, I didn't realize that modifying the third argument to .map was cumulative. I saw the .map().filter() and thought "This would make a great array comprehension!", but the lack of index in array comprehensions killed it and it ended up at the same length: s=>c=>[for(x of(i=0,z=[...s]))if(--i&&x!=c)(z[~i]=~i?'':x,z.join``)] (btw, I count 68 bytes for all of these.) – ETHproductions – 2016-11-23T01:46:28.537

1Actually, by rearranging the params you can get the array comprehension down to 66: ([...z],c,i=0)=>[for(x of z)if(--i&&x!=c)(z[~i]=~i?'':x,z.join``)] – ETHproductions – 2016-11-23T01:51:05.800

@ETHproductions can't believe I was wrong in byte count again. Anyway, thanks to making me think again about it, so I got 64 with standard ES6 – edc65 – 2016-11-23T08:23:32.087

2

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.

paldir

Posted 2016-11-19T19:18:53.747

Reputation: 109

1Won't work if the input char is present more than once in a row. Ex : codeegolf e would give ce instead of cee. – psycho – 2016-11-21T12:56:10.943

@psycho I swapped if with while and it works. – paldir – 2016-11-21T13:14:56.663

Better ! But it can be shorter. I'll post my own ! – psycho – 2016-11-21T13:31:27.617

1Create a variable for s.Length to save one byte: 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);}} – TheLethalCoder – 2016-11-22T09:30:53.530

2

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.

psycho

Posted 2016-11-19T19:18:53.747

Reputation: 121

1Nice trick with using not generic collection. But it won't work, if last char is not special char c. In that case loop will try to work forever. – paldir – 2016-11-21T13:44:23.053

1@paldir Woops, you're right ! Turning my brain on this time, found a better (and shorter !) way. – psycho – 2016-11-21T14:48:29.980

You could remove the parenthesis of the for loop to save 2 bytes. – PmanAce – 2016-11-21T17:32:02.423

@PmanAce Sorry, what do you mean ? Which parenthesis ? – psycho – 2016-11-21T17:46:50.317

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;
}
– PmanAce – 2016-11-21T19:00:22.987

@PmanAce Hmm... What you wrote is exactly my code with spaces. Wild guess : did you mean the brackets ? They're only present in the ungolfed version :) – psycho – 2016-11-22T19:20:30.427

Ah ok sorry, my bad then, I assumed your ungolfed version was just indented. :) – PmanAce – 2016-11-22T19:42:45.630

2

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

Blue

Posted 2016-11-19T19:18:53.747

Reputation: 26 661

Could you add an explanation? – Esolanging Fruit – 2016-12-02T22:50:47.003

@Challenger5 done and golfed 2 bytes! – Blue – 2016-12-03T11:24:49.937

2

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

dfundako

Posted 2016-11-19T19:18:53.747

Reputation: 141

Good use of patindex, but the alphabet example doesn't seem quite right, it displays aaphabet down through aaa. Also worth mentioning this should be run on a server or database with a case-sensitive collation, otherwise the upperCASE example also fails, displaying ueE on its final row. – BradC – 2018-05-21T16:54:00.970

2

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]

Lulhum

Posted 2016-11-19T19:18:53.747

Reputation: 381

2

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

rnso

Posted 2016-11-19T19:18:53.747

Reputation: 1 635

2

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

rabidaudio

Posted 2016-11-19T19:18:53.747

Reputation: 21

Welcome to PPCG! Can some of the whitespace towards the end of the code be removed? – ETHproductions – 2016-12-02T03:00:47.617

@ETHproductions unfortunately not, the ternary operator and the while need spaces to compile. I also played with typealiasing String and trying to set print to a closure, but they didn't save any space. – rabidaudio – 2016-12-02T05:10:08.160

1

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.

Greg Martin

Posted 2016-11-19T19:18:53.747

Reputation: 13 940

Oh, c'mon, we both know that Mathematica isn't imperative – LegionMammal978 – 2016-11-20T02:50:24.887

1<waves a white flag> – Greg Martin – 2016-11-20T19:15:59.203

1

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>

Bassdrop Cumberwubwubwub

Posted 2016-11-19T19:18:53.747

Reputation: 5 707

1

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.

Vedvart1

Posted 2016-11-19T19:18:53.747

Reputation: 179

As per this post, I think you can make the first line a,b=input(), but you would have to use Python 2, which would make it so that you could remove the parenthesis with print. You would provide the input like this 'Hello, World', 'o'.

– nedla2004 – 2016-11-20T15:58:16.627

Hmmm...for the first test case (codegolf.stackexchange.com,e) I just get the output cececec. – R. Kap – 2016-11-21T04:08:47.397

This solution doesn't output the intermediate strings – Lulhum – 2016-11-22T15:59:08.903

1

Groovy, 34 bytes

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

Magic Octopus Urn

Posted 2016-11-19T19:18:53.747

Reputation: 19 422

1Its so weird to get an old answer upvoted... – Magic Octopus Urn – 2017-04-28T19:55:45.100

1

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

Huge thanks to ETHproductions for the help!

Oliver

Posted 2016-11-19T19:18:53.747

Reputation: 7 160

Welcome to PPCG! We don't allow programs that rely on existing variables, but you can turn this into a function returning an array: function(f,t){a=[];a.push(f[0]);for(var i=0;i<f.length;i++)if(f[i]==t)a.push(f[i]);return a} – ETHproductions – 2016-12-01T18:13:31.443

Also, this doesn't actually answer the question; entries should create a list of the strings, and this seems to only output multiple copies of t. – ETHproductions – 2016-12-01T18:16:33.280

@ETHproductions You're right, I'll try to re-do it. Here's what I have to far function(p,k){for(var i=0;i<a.length;i++)if(p[i]!=k){p = p.replace(p[i],'');console.log(p)}} I'm trying to fix an issue where the length of my loop is decreasing while iterating. Thanks for the feedback. – Oliver – 2016-12-01T19:06:42.960

I think you could do function(p,k){for(var i=0,l=p.length;i<l;i++)if(p[i]!=k){p=p.replace(p[i],'');console.log(p)}}. – ETHproductions – 2016-12-01T19:09:22.120

I'm getting the following with that function http://imgur.com/a/Oaeyr

– Oliver – 2016-12-01T19:24:06.433

Ah, try this: function(p,k){for(var i=0;i<p.length;)p[i]!=k?console.log(p=p.replace(p[i],'')):i++} – ETHproductions – 2016-12-01T19:28:08.933

Nice! That works. Just need to change the starting index to 1 so we can keep the first letter of the phrase. – Oliver – 2016-12-01T20:01:56.087

I think the best way to do that would be this, which is 91 bytes.

– ETHproductions – 2016-12-01T20:13:58.070

I was using slice before I realized I could just replace the character with an empty string. What's the advantage in using slice? – Oliver – 2016-12-01T20:27:58.287

If you come across the first char later in the string, .replace will remove the first char instead. For example, "cdedc","e" would output cedc cec ec. – ETHproductions – 2016-12-01T20:30:10.070

1

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.

Xanderhall

Posted 2016-11-19T19:18:53.747

Reputation: 1 236

Hello from the future! Looks like the character input doesn't need to be regex-safe, so you'll have to do some escaping. Consider input foo, ^. – Jakob – 2018-05-21T15:32:28.870

1

SmileBASIC, 65 bytes

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

12Me21

Posted 2016-11-19T19:18:53.747

Reputation: 6 110

1

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

Greedo

Posted 2016-11-19T19:18:53.747

Reputation: 267

Welcome to the site! :) – James – 2017-04-28T19:15:43.837

Line endings are counted as 1 byte, so the VBA byte count is correct. – Esolanging Fruit – 2017-04-28T20:59:05.293

There are unfortunately a couple of things wrong with this response. 1) the VBA answer fails to output the unchanged string and 2) the Excel response does not produce all lines of output – Taylor Scott – 2018-05-21T15:05:41.360

You can remove a good bit of whitespace to get this down to 125 bytes, Sub x(s,v) Debug.?s For i=2To Len(s) c=Mid(s,i,1) If c=""Then End If v<>c Then s=Replace(s,c,"",,1):i=1:Debug.?s Next End Sub – Taylor Scott – 2018-05-21T15:07:42.380

1

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()])

Karlis255

Posted 2016-11-19T19:18:53.747

Reputation: 41

@Hat Wizard Because otherwise it would call [None, None, None, None, ...], and since lists aren't callable, it would fail. – Karlis255 – 2018-05-21T17:06:12.460

1

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!

David

Posted 2016-11-19T19:18:53.747

Reputation: 11

Welcome to the site! Is it possible to edit in a link to an online testing environment, such as Try it online!, so that others can verify your answer? It also looks like you can make a few golfs, such as removing continue: Try it online!

– caird coinheringaahing – 2019-09-05T07:50:19.753

@cairdcoinheringaahing Thank you for the advice! – David – 2019-09-05T08:13:51.947

0

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)

dvorkanton

Posted 2016-11-19T19:18:53.747

Reputation: 11

Defining a function will be much shorter. 62 characters: def _(s,c): p=s[0] for h in s:p+=s[:h==c];s=s[1:];print(p+s) (2 line breaks as needed) – AnnanFay – 2016-11-19T22:53:25.503

1This prints extra lines when c is encountered (e.g. cegolf.stackexchange.com is printed twice with c='e') – Jonathan Allan – 2016-11-20T04:48:39.580

0

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

Sethi

Posted 2016-11-19T19:18:53.747

Reputation: 101

1Can you please provide a working snippet? I can't seem to get this to work – Bassdrop Cumberwubwubwub – 2016-11-19T23:53:48.793

It actually wasn't working to begin with. I forgot I intended to wrap the function with another. I've fixed it now. I'm on my iPad, procrastinating - don't even know how I'd add a working snippet lol – Sethi – 2016-11-20T00:07:13.247

0

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);}

o79y

Posted 2016-11-19T19:18:53.747

Reputation: 509

0

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

Ray

Posted 2016-11-19T19:18:53.747

Reputation: 1 488

0

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

sonrad10

Posted 2016-11-19T19:18:53.747

Reputation: 535

You can use [*input()] rather than list(input()), and you can omit the parenthesis around [b[0],input()]. – Esolanging Fruit – 2017-04-29T00:54:27.410

Also, this fails for input interesting and e (the second i is kept). – Esolanging Fruit – 2017-04-29T00:56:42.377

@Challenger5 for the [*interesting] I am getting a syntax error: SyntaxError : can use starred expression only as assignment target. Also, sorry about the error; I had misunderstood the question, and am fixing it. – sonrad10 – 2017-04-29T08:40:53.290

Just realised; in the above comment, I meant to put [*input()] – sonrad10 – 2017-04-29T08:57:07.490

TIO Link – Esolanging Fruit – 2017-04-30T04:51:32.523

0

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

sprague44

Posted 2016-11-19T19:18:53.747

Reputation: 81

You might want ot read this: http://codegolf.stackexchange.com/questions/3885/tips-for-golfing-in-scala

– corvus_192 – 2016-11-23T13:04:00.073

0

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));};

adrianmp

Posted 2016-11-19T19:18:53.747

Reputation: 1 592

0

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.

Mitchell Spector

Posted 2016-11-19T19:18:53.747

Reputation: 3 392

You could squeeze all the code on to one line and separate instructions with semicolons and save about 2 bytes. – ckjbgames – 2017-02-15T00:31:58.173

@ckjbgames I thought that I only had newlines that replaced either a semicolon or a space, so it would be the same number of bytes (it's clearer with newlines, so I like doing that if doesn't cost any bytes). But it turns out that there was one extra newline that added an unnecessary byte, which I've taken out -- thank you. It's just one byte though, unless I'm missing something. – Mitchell Spector – 2017-02-15T00:39:40.870

You could also remove the newline before the closing brace and save 1 more byte. – ckjbgames – 2017-02-15T00:41:49.047

@ckjbgames That doesn't work -- try it out. If you take out that newline, you need to replace it with a semicolon. (If it works for you, what version of bash are you using?) – Mitchell Spector – 2017-02-15T00:43:39.170

Actually, it would not save a byte. Sorry for my mistake there. – ckjbgames – 2017-02-15T00:44:39.283

I appreciate the one byte you did save me, and the correction of my misimpression that a semicolon or newline was needed after the for((...)) construct, before the {. – Mitchell Spector – 2017-02-15T00:46:01.530

Also, in your variable assignment at the beginning, you do not need to quote $1. – ckjbgames – 2017-02-16T16:08:22.617

@ckjbgames Thank you -- I put that in to take care of, for example, an asterisk in the argument, but I forgot that pathname expansion isn't done on the right-hand side of an assignment statement. – Mitchell Spector – 2017-02-16T18:59:10.623

In code golf, it is a good thing to know that, most of the time, you do not have to handle exceptions. – ckjbgames – 2017-02-16T19:22:42.783

0

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

Carcigenicate

Posted 2016-11-19T19:18:53.747

Reputation: 3 295

0

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

Jörg Hülsermann

Posted 2016-11-19T19:18:53.747

Reputation: 13 026

0

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

Bubbler

Posted 2016-11-19T19:18:53.747

Reputation: 16 616

0

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!

Taylor Scott

Posted 2016-11-19T19:18:53.747

Reputation: 6 709

0

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

recursive

Posted 2016-11-19T19:18:53.747

Reputation: 8 616

0

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.

Veskah

Posted 2016-11-19T19:18:53.747

Reputation: 3 580

0

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.

AlexRacer

Posted 2016-11-19T19:18:53.747

Reputation: 979

0

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

Andrew Baumher

Posted 2016-11-19T19:18:53.747

Reputation: 351

-1

JavaScript (ES6), 56 Bytes

F=(s,c)=>s[0]+s.slice(1).replace(eval(`/[^${c}]/g`),'');

Trey it right here:

F=(s,c)=>s[0]+s.slice(1).replace(eval(`/[^${c}]/g`),'');

function Answer() {
  O.textContent=F(S.value,C.value[0])
}
Answer()
<input id=S value='Make a "Ceeeeeeee" program' oninput='Answer()'>
<input id=C value='e' oninput='Answer()'>
<pre id=O></pre>

Unicornist

Posted 2016-11-19T19:18:53.747

Reputation: 101

Shortest JS(ES6) answer so far... – Unicornist – 2016-11-23T09:25:56.227

Welcome to PPCG :) . You need to print the history step by step as mentionned in the question. – Osable – 2016-11-23T09:31:20.710

hmm. so I assume other JS answers are also incorrect. Am I right? – Unicornist – 2016-11-23T09:40:41.263

You are 50% right on that. ;) 3 of them are incorrect, but Neil's, edc65's and Bassdrop Cumberwubwubwub's answers are correct.

– manatwork – 2016-11-23T09:51:54.650