98
\$\begingroup\$

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.

\$\endgroup\$
9
  • 28
    \$\begingroup\$ Kinda random, but +1 \$\endgroup\$ Nov 19, 2016 at 19:28
  • 28
    \$\begingroup\$ +1 for Meeeeeeeeegram \$\endgroup\$
    – FlipTack
    Nov 19, 2016 at 20:15
  • \$\begingroup\$ In the case that it returns an array, do each of the elements have to include a trailing newline? \$\endgroup\$ Nov 19, 2016 at 20:24
  • 4
    \$\begingroup\$ Meeeeeeeeeeeeem \$\endgroup\$
    – Mathime
    Nov 23, 2016 at 7:52
  • 2
    \$\begingroup\$ 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? \$\endgroup\$
    – user61264
    Dec 2, 2016 at 8:30

61 Answers 61

1
\$\begingroup\$

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>

\$\endgroup\$
1
\$\begingroup\$

Groovy, 34 bytes

{a,b->a.inject{i,r->i+=r==b?b:""}}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Its so weird to get an old answer upvoted... \$\endgroup\$ Apr 28, 2017 at 19:55
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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, ^. \$\endgroup\$
    – Jakob
    May 21, 2018 at 15:32
1
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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'. \$\endgroup\$
    – nedla2004
    Nov 20, 2016 at 15:58
  • \$\begingroup\$ Hmmm...for the first test case (codegolf.stackexchange.com,e) I just get the output cececec. \$\endgroup\$
    – R. Kap
    Nov 21, 2016 at 4:08
  • \$\begingroup\$ This solution doesn't output the intermediate strings \$\endgroup\$
    – Lulhum
    Nov 22, 2016 at 15:59
1
\$\begingroup\$

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!

\$\endgroup\$
10
  • \$\begingroup\$ 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} \$\endgroup\$ Dec 1, 2016 at 18:13
  • \$\begingroup\$ 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. \$\endgroup\$ Dec 1, 2016 at 18:16
  • \$\begingroup\$ @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. \$\endgroup\$
    – Oliver
    Dec 1, 2016 at 19:06
  • \$\begingroup\$ 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)}}. \$\endgroup\$ Dec 1, 2016 at 19:09
  • \$\begingroup\$ I'm getting the following with that function imgur.com/a/Oaeyr \$\endgroup\$
    – Oliver
    Dec 1, 2016 at 19:24
1
\$\begingroup\$

SmileBASIC, 65 bytes

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

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

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to the site! :) \$\endgroup\$
    – DJMcMayhem
    Apr 28, 2017 at 19:15
  • \$\begingroup\$ Line endings are counted as 1 byte, so the VBA byte count is correct. \$\endgroup\$ Apr 28, 2017 at 20:59
  • \$\begingroup\$ 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 \$\endgroup\$ May 21, 2018 at 15:05
  • \$\begingroup\$ 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 \$\endgroup\$ May 21, 2018 at 15:07
1
\$\begingroup\$

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()])
\$\endgroup\$
1
  • \$\begingroup\$ @Hat Wizard Because otherwise it would call [None, None, None, None, ...], and since lists aren't callable, it would fail. \$\endgroup\$ May 21, 2018 at 17:06
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ 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! \$\endgroup\$ Sep 5, 2019 at 7:50
  • \$\begingroup\$ @cairdcoinheringaahing Thank you for the advice! \$\endgroup\$
    – David
    Sep 5, 2019 at 8:13
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
2
  • \$\begingroup\$ 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) \$\endgroup\$
    – AnnanFay
    Nov 19, 2016 at 22:53
  • 1
    \$\begingroup\$ This prints extra lines when c is encountered (e.g. cegolf.stackexchange.com is printed twice with c='e') \$\endgroup\$ Nov 20, 2016 at 4:48
0
\$\begingroup\$

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])
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you please provide a working snippet? I can't seem to get this to work \$\endgroup\$ Nov 19, 2016 at 23:53
  • \$\begingroup\$ 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 \$\endgroup\$
    – Sethi
    Nov 20, 2016 at 0:07
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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);}
\$\endgroup\$
0
\$\begingroup\$

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));};
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
1
0
\$\begingroup\$

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.

\$\endgroup\$
9
  • \$\begingroup\$ You could squeeze all the code on to one line and separate instructions with semicolons and save about 2 bytes. \$\endgroup\$
    – ckjbgames
    Feb 15, 2017 at 0:31
  • \$\begingroup\$ @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. \$\endgroup\$ Feb 15, 2017 at 0:39
  • \$\begingroup\$ You could also remove the newline before the closing brace and save 1 more byte. \$\endgroup\$
    – ckjbgames
    Feb 15, 2017 at 0:41
  • \$\begingroup\$ @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?) \$\endgroup\$ Feb 15, 2017 at 0:43
  • \$\begingroup\$ Actually, it would not save a byte. Sorry for my mistake there. \$\endgroup\$
    – ckjbgames
    Feb 15, 2017 at 0:44
0
\$\begingroup\$

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)))))
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ You can use [*input()] rather than list(input()), and you can omit the parenthesis around [b[0],input()]. \$\endgroup\$ Apr 29, 2017 at 0:54
  • \$\begingroup\$ Also, this fails for input interesting and e (the second i is kept). \$\endgroup\$ Apr 29, 2017 at 0:56
  • \$\begingroup\$ @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. \$\endgroup\$
    – AvahW
    Apr 29, 2017 at 8:40
  • \$\begingroup\$ Just realised; in the above comment, I meant to put [*input()] \$\endgroup\$
    – AvahW
    Apr 29, 2017 at 8:57
  • \$\begingroup\$ TIO Link \$\endgroup\$ Apr 30, 2017 at 4:51
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 150, var s:string;c:char;i:word;begin read(c,s);i:=2;while i<=length(s)do begin if c=s[i]then inc(i)else begin writeln(s);delete(s,i,1)end;end;write(s)end.. Input c before s. \$\endgroup\$
    – tsh
    Dec 24, 2021 at 7:48
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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)

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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