Remove all occurrences of the first letter of a string from the entire string

24

1

Given an input string only containing the characters A-Z, a-z, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is A remove all As and as, if the first character is (space) remove all spaces), and print the output.

Example cases:

  • Testing Testing One Two Three -> esing esing One wo hree
  • Programming Puzzles and Code Golf -> rogramming uzzles and Code Golf
  • How much wood would a woodchuck chuck if a woodchuck could chuck wood -> ow muc wood would a woodcuck cuck if a woodcuck could cuck wood
  • {space}hello world -> helloworld
  • welcome to WATER WORLD -> elcome to ATER ORLD

This is , shortest code in bytes wins!

Notes:

  • Input will always be 2 or more valid characters.
  • Output will never be an empty string.

GamrCorps

Posted 2015-10-24T04:47:29.087

Reputation: 7 058

Do we need to handle the case where output is the empty string? What if input is the empty string? – lirtosiast – 2015-10-24T17:23:29.447

@ThomasKwa you may assume output will alway be 2 or more characters – GamrCorps – 2015-10-24T17:51:51.850

@ThomasKwa and output will never be empty – GamrCorps – 2015-10-24T17:52:14.057

Answers

9

Pyth, 7 bytes

-zrBhz2

Try it online: Demonstration or Test Suite

Nice. The new bifurcate operator (only 8 days old) helps here to save one char. I think this is the first code, that uses this feature.

Explanation

-zrBhz2   implicit: z = input string
    hz    take the first character of z
  rB  2   B generates a list, containing the original char and the  
          result of r.2 applied to the char, which swaps the case
-z        remove these two chars from z and print the result 

Jakube

Posted 2015-10-24T04:47:29.087

Reputation: 21 462

2Neat, didn't know about that. +1 – FryAmTheEggman – 2015-10-24T17:05:59.167

14

brainfuck, 219 bytes

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

(Requires tape that either allows the pointer to go to the negatives or loops to the end if it tries. Also requires , to return 0 at EOF. In my experience, most interpreters meet these requirements by default.)

This actually turned out to be pretty easy! I wouldn't be surprised if it's golfable (I have some idea of where there might be wasted bytes but I'm not super sure if it'll pan out). Still, getting it work wasn't really a challenge at all.

This code treats everything with an ASCII value below 97 as an uppercase character. If the first character is space, it'll try to remove any occurrences of a "lowercase space" (i.e. chr(32+32), i.e. @) from the string. This is okay, because only letters and spaces will ever be present.

With comments:

to make comments shorter: everywhere it says "fc" means "first character"

#################################### GET FC ####################################

+[+[>+<+<]>]        shortest way to get 96
                    any number above 89 and less than 97 would work because this
                    is only for figuring out if the first character is capital

,[<+<+>>-]          create two copies of the first character


### current tape: | fc | fc | 000 | 096 | ###
###      pointer:              ^          ###

########################### FIND MAX(FC MINUS 96; 0) ###########################


>[                  96 times:

  <<                  go to the cell with the first char

  [->]                if not 0: sub one and move right


  ### current tape: | fc | char being worked on | 000 | 096 | ###
  ###      pointer:                           ^ OR ^          ###      


  >[<]>               collapse the wavefunction; sync the branches

-]


### current tape: | fc | fc is lowercase ? nonzero : zero | 000 | 000 | ###
###      pointer:                                                  ^    ###

############################# GET BOTH CASES OF FC #############################

++++[<++++++++>-]   get 32 (add to uppercase character to get lowercase)

<<[                 if the character is already lowercase:

  [-]                 clear the lowercase flag

  ----[>-<----]>-     sub 64 from the cell with 32

<]

<[>+>+<<-]          add fc to the 32 or minus 32 to get both cases


### current tape: | 000 | fc | other case of fc | ###
###      pointer:    ^                            ###

###################### LOOP THROUGH REMAINING CHARACTERS #######################

<,[                 for each character:

  [>+>>>+>>+>+<<<<<<<-]
                      make four copies
                      (only 3 are strictly needed; 4th will resync a branch)

  >>                  go to the first case of fc

  [<<+>>-]<<[>->+<<-] subtract one case of fc from one copy

  >[[-]+<]            if the result is nonzero set it to 1

  >[>]<<              go to the other case of fc (and resync branches)

  [>>+<<-]>>[<-<+>>-] subtract other case of fc from other copy

  <[[-]+>]            if the result is nonzero set it to 1

  >>[<]               resync branches using extra copy

  <<<<[>>>+<<<-]>>>   add results together

  -                   subtract 1

   if the character exactly matched either case: 1 plus 0 minus 1 = 0
  if the character exactly matched neither case: 1 plus 1 minus 1 = 1
    if the character exactly matched both cases: impossible

  [                   if the result is 1:

    >>.<<               output character

    -                   set cell to 0 to kill loop

  ]

  >>>[[-]<]           clean up remaining copies

  <<<<<,              get next character; or end loop if done

]

undergroundmonorail

Posted 2015-10-24T04:47:29.087

Reputation: 5 897

Please don't golf this down too much. c: I worked so hard... – Addison Crump – 2015-10-25T21:44:52.813

13

Perl, 13 bytes

#!perl -p
/./,s/$&//gi

Counting the shebang as one, input is taken from stdin.


Sample Usage

$ echo Testing Testing One Two Three | perl remove-first.pl
esing esing One wo hree

$ echo \ Testing Testing One Two Three | perl primo-remove.pl
TestingTestingOneTwoThree

primo

Posted 2015-10-24T04:47:29.087

Reputation: 30 891

Nice. I was thinking about how Perl would probably do badly because of the need to write substr but of course you came up with a much better way! – hobbs – 2015-10-24T06:10:21.050

Why do you count hashbang as one byte? – Zereges – 2015-10-24T09:57:45.873

@Zereges the shebang line is not necessary, if the script is invoked as perl -p script.pl. Command line options are customarily counted as one byte each, at least on this site. – primo – 2015-10-24T10:00:31.687

@primo I see, thanks. – Zereges – 2015-10-24T10:08:11.313

10

CJam, 8 bytes

q(_32^+-

Try it online in the CJam interpreter.

How it works

q        e# Read all input from STDIN.
 (       e# Shift out the first character.
  _32^   e# Push a copy and XOR its character code with 32.
         e#   For a letter, this swaps its case.
         e#   For a space, this pushes a null byte.
      +  e# Concatenate these two characters.
       - e# Remove all occurrences of both from the input string.

Dennis

Posted 2015-10-24T04:47:29.087

Reputation: 196 637

I originally created this challenge to learn CJam, and I never knew about the XOR thing! – GamrCorps – 2015-10-24T05:17:42.183

2I personally find it surprising that any language - with exception to perhaps sed - could beat perl in this challenge. – primo – 2015-10-24T06:04:59.147

@primo - You haven't noticed that CJam and/or Pyth pretty much win 99% of these? Perl did pretty good though, considering it's the only one not specifically designed as a golfing language. – Darrel Hoffman – 2015-10-24T13:29:11.410

Pyth and CJam's operator overloading is ridiculous. minus(string,string) performing per-character removal is not a core operation in any other language I've encountered. – Sparr – 2015-10-25T18:26:23.010

@Sparr APL has the same built-in. (It's called ~ though.) – Dennis – 2015-10-25T18:29:54.230

7

Pyth, 8 bytes

-zr*2hz3

Try it online

Uses Pyth's version of python's str.title to convert a string of the first letter twice into the form "<Upper><Lower>". Then it removes each element from the input that is in that string. Spaces work fine because they are unaffected by str.title.

FryAmTheEggman

Posted 2015-10-24T04:47:29.087

Reputation: 16 206

5

JavaScript (ES6), 38 36 bytes

This does not depend on the flags parameter which is Mozilla-specific.

f=x=>x.replace(RegExp(x[0],'gi'),'')

CoffeeScript, 39 37 bytes

For once it's shorter in JS than CoffeeScript!

f=(x)->x.replace RegExp(x[0],'gi'),''

rink.attendant.6

Posted 2015-10-24T04:47:29.087

Reputation: 2 776

3At least in the browsers I tried, the new is optional, so RegExp(x[0],'gi') is shorter. – Neil – 2015-10-24T15:05:20.390

5

MATLAB, 28 bytes

@(S)S(lower(S)~=lower(S(1)))

Stewie Griffin

Posted 2015-10-24T04:47:29.087

Reputation: 43 471

4

PHP, 41 bytes

Takes one command-line argument. Short open tags need to be enabled for PHP < 5.4.

<?=str_ireplace($argv[1][0],'',$argv[1]);

rink.attendant.6

Posted 2015-10-24T04:47:29.087

Reputation: 2 776

1You can shorten it by declaring a variable containing $argv[1] : <?=str_ireplace(($a=$argv[1])[0],'',$a); – Benoit Esnard – 2015-10-25T10:05:35.623

3

Minkolang 0.9, 23 33 bytes

No way this will win but eh, it's fun!

" Z"od0c`1c*-$I[odd0c`1c*-2c=?O].

Try it here.

Explanation

" Z"                                 Makes it easier to uppercase
    od                               Take first character of input and duplicate
      0c`1c*-                        Uppercase if needed
             $I[               ]     Loop over the input
                odd                  Take character from input and duplicate twice
                   0c`1c*-           If it's lowercase, uppercase it.
                          0c=?       Check to see if it's equal to first character
                              O      If not, output as character
                                .    Exit

(This might fail in some edge cases, like if the first character is a symbol.)

El'endia Starman

Posted 2015-10-24T04:47:29.087

Reputation: 14 504

3

Perl, 27 bytes

This is a complete program, although it's just based on 2 regexes that could probably copied into a Retina program to save bytes on I/O.

$_=<>;m/(.)/;s/$1//gi;print

Edit: Looks like this has already been beaten with somebody using the -p option. Oh, and using $& instead of $1.

PhiNotPi

Posted 2015-10-24T04:47:29.087

Reputation: 26 739

1Even if the entire shebang is counted (i.e. a "complete" program), #!perl -p is still two bytes shorter than $_=<>;print. – primo – 2015-10-24T06:01:11.537

@primo I've never used any of the options in my golfs. I just googled what the -p option does. There's not really any edits that I can make to my answer without just making it identical to yours. – PhiNotPi – 2015-10-24T06:07:25.637

3

TECO, 15 14 bytes

Editing text? When in doubt, use the Text Editor and COrrecter!

After much trial-and-error (mostly error), I think this is the shortest generic TECO program that will do the job.

0,1XA<S^EQA$-D>

Or, in human-readable form

0,1XA    ! Read the first character of the string into the text area of !
         ! Q-buffer A.                                                  !
<        ! Loop,                                                        !
S^EQA$   ! searching for the text in Q-buffer A in either lowercase or  !
         ! uppercase,                                                   !
-D       ! and deleting it,                                             !
>        ! until the search fails.                                      !

$ represents the escape key, and ^E represents the sequence CTRL+E. Depending on the flavor of TECO you're using, it may recognize these ASCII substitutions, or it may not.

According to the manual, some dialects of TECO accept this 13-byte version (using a find-and-delete command instead of separate "find" and "delete" commands) instead:

0,1XA<FD^EQA$>

Mark

Posted 2015-10-24T04:47:29.087

Reputation: 2 099

3

Pip, 8 bytes

aR-Xa@0x

Takes the string as a command-line argument (will need to be quoted if it contains spaces). Explanation:

          a gets cmdline arg; x is "" (implicit)
    a@0   First character of a
   X      Convert to regex
  -       Make regex case-insensitive
aR     x  Replace all matches of that regex in a with empty string
          Autoprint (implicit)

This solution has the extra bonus of working on strings containing any printable ASCII characters. (The X operator backslash-escapes anything that's not alphanumeric.)

DLosc

Posted 2015-10-24T04:47:29.087

Reputation: 21 213

3

Python, 66 char

a=raw_input()
print a.replace(a[0],'').replace(a[0].swapcase(),'')

TheDoctor

Posted 2015-10-24T04:47:29.087

Reputation: 7 793

5@ThomasKwa how about no. – TheDoctor – 2015-10-24T22:35:41.897

3

Julia, 34 bytes

s->replace(s,Regex(s[1:1],"i"),"")

This creates an unnamed function that accepts a string and returns a string. It constructs a case-insensitive regular expression from the first character in the input and replaces all occurrences of that with an empty string.

Alex A.

Posted 2015-10-24T04:47:29.087

Reputation: 23 761

2

Python, 61 bytes (way too many)

lambda x:"".join(map(lambda y:(y.lower()!=x[0].lower())*y,x))

I imagine there is a better way to go about doing this, but I can't seem to find it. Any ideas on removing the "".join(...)?

cole

Posted 2015-10-24T04:47:29.087

Reputation: 3 526

1@ThomasKwa perhaps you should submit that as your own answer; it seems too different from mine to count as my submission. – cole – 2015-10-24T07:28:04.470

@ThomasKwa Shorter to do x[0]+x[0].swapcase(). – xnor – 2015-10-24T08:08:20.077

1@ThomasKwa Or, stealing from FryAmTheEggman's Pyth solution, (x[0]*2).title(). – xnor – 2015-10-24T09:32:50.633

@xnor yeah, I found that when I read theirs a few hours ago. – lirtosiast – 2015-10-24T16:09:25.150

lambda x:x.replace(x[0].upper(),'').replace(x[0].lower(),'') - 60 bytes – Mego – 2015-10-24T19:59:38.910

2

Mathematica, 47 bytes

StringDelete[#,#~StringTake~1,IgnoreCase->1>0]&

LegionMammal978

Posted 2015-10-24T04:47:29.087

Reputation: 15 731

2

R, 43 bytes

cat(gsub(substr(s,1,1),"",s<-readline(),T))

This is a full program that reads a line from STDIN and writes the modified result to STDOUT.

Ungolfed:

# Read a line from STDIN
s <- readline()

# Replace all occurrences of the first character with an empty
# string, ignoring case
r <- gsub(substr(s, 1, 1), "", s, ignore.case = TRUE)

# Write the result to STDOUT
cat(r)

Alex A.

Posted 2015-10-24T04:47:29.087

Reputation: 23 761

2

Ruby, 25 bytes

Anonymous function:

->s{s.gsub /#{s[0]}/i,""}

Full prgram, 29 bytes:

puts gets.gsub /#{$_[0]}/i,""

daniero

Posted 2015-10-24T04:47:29.087

Reputation: 17 193

2

Ouroboros, 61 bytes

Hey, it's shorter than C++! Ha.

i..91<\64>*32*+m1(
)L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo

In Ouroboros, each line of the program represents a snake with its tail in its mouth. Control flow is accomplished by eating or regurgitating sections of tail, with a shared stack to synchronize between snakes.

Snake 1

i. reads a character from input and duplicates it. .91<\64>*32* pushes 32 if the character was an uppercase letter, 0 otherwise. +ing that to the character converts uppercase letters to lowercase while leaving lowercase letters and spaces unchanged. All this has been taking place on snake 1's stack, so we now push the value to the shared stack (m) for snake 2 to process. Finally, 1( eats the last character of snake 1's tail. Since that's where the instruction pointer is, the snake dies.

Snake 2

) has no effect the first time through. L!34* pushes 34 if the shared stack is empty, 0 otherwise. We then . dup and ( eat that many characters.

  • If the shared stack was empty, this puts the end of the snake right after the ( we just executed. Therefore, control loops back to the beginning of the line, where ) regurgitates the characters we just ate (having previously pushed an extra copy of 34) and repeat the stack-length test.
  • If the shared stack was not empty, no characters are eaten, ';' drops the extra 0, and execution continues:

Si switches to the shared stack and inputs another character. .1+!24* pushes 24 if that character was -1 / EOF, 0 otherwise. On EOF, ( swallows 24 characters--including the IP--and the snake dies. Otherwise, execution continues.

Y yanks a copy of the top of the shared stack (the character we just read) to snake 2's own stack for future use. Then .@@.@=@.@32-=\@+2* calculates whether the new character is equal to the first character or to the first character minus 32, pushing 2 if so and 0 if not. We . duplicate and ( eat that many characters:

  • If the characters matched, we go straight back to the head of the snake, where ( regurgitates the 2 characters we just ate and execution proceeds with the next character.
  • If not, we yank the character back from snake 2's stack, output it, and then loop.

See it in action

// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
    return "" + this.stack;
  }

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
    if (!this.alive) {
      return null;
    }
    if (this.wait > 0) {
      this.wait--;
      return null;
    }
    var instruction = this.code.charAt(this.ip);
    var output = null;
    if (this.partialString !== null) {
      // We're in the middle of a double-quoted string
      if (instruction == '"') {
        // Close the string and push its character codes in reverse order
        for (var i = this.partialString.length - 1; i >= 0; i--) {
          this.currStack.push(this.partialString.charCodeAt(i));
        }
        this.partialString = null;
      } else {
        this.partialString += instruction;
      }
    } else if (instruction == '"') {
      this.partialString = "";
    } else if ("0" <= instruction && instruction <= "9") {
      if (this.partialNumber !== null) {
        this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
      } else {
        this.partialNumber = instruction;
      }
      next = this.code.charAt((this.ip + 1) % this.length);
      if (next < "0" || "9" < next) {
        // Next instruction is non-numeric, so end number and push it
        this.currStack.push(+this.partialNumber);
        this.partialNumber = null;
      }
    } else if ("a" <= instruction && instruction <= "f") {
      // a-f push numbers 10 through 15
      var value = instruction.charCodeAt(0) - 87;
      this.currStack.push(value);
    } else if (instruction == "$") {
      // Toggle the current stack
      if (this.currStack === this.ownStack) {
        this.currStack = this.program.sharedStack;
      } else {
        this.currStack = this.ownStack;
      }
    } else if (instruction == "s") {
      this.currStack = this.ownStack;
    } else if (instruction == "S") {
      this.currStack = this.program.sharedStack;
    } else if (instruction == "l") {
      this.currStack.push(this.ownStack.length);
    } else if (instruction == "L") {
      this.currStack.push(this.program.sharedStack.length);
    } else if (instruction == ".") {
      var item = this.currStack.pop();
      this.currStack.push(item);
      this.currStack.push(item);
    } else if (instruction == "m") {
      var item = this.ownStack.pop();
      this.program.sharedStack.push(item);
    } else if (instruction == "M") {
      var item = this.program.sharedStack.pop();
      this.ownStack.push(item);
    } else if (instruction == "y") {
      var item = this.ownStack.top();
      this.program.sharedStack.push(item);
    } else if (instruction == "Y") {
      var item = this.program.sharedStack.top();
      this.ownStack.push(item);
    } else if (instruction == "\\") {
      var top = this.currStack.pop();
      var next = this.currStack.pop()
      this.currStack.push(top);
      this.currStack.push(next);
    } else if (instruction == "@") {
      var c = this.currStack.pop();
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(c);
      this.currStack.push(a);
      this.currStack.push(b);
    } else if (instruction == ";") {
      this.currStack.pop();
    } else if (instruction == "+") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a + b);
    } else if (instruction == "-") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a - b);
    } else if (instruction == "*") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a * b);
    } else if (instruction == "/") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a / b);
    } else if (instruction == "%") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a % b);
    } else if (instruction == "_") {
      this.currStack.push(-this.currStack.pop());
    } else if (instruction == "I") {
      var value = this.currStack.pop();
      if (value < 0) {
        this.currStack.push(Math.ceil(value));
      } else {
        this.currStack.push(Math.floor(value));
      }
    } else if (instruction == ">") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a > b));
    } else if (instruction == "<") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a < b));
    } else if (instruction == "=") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a == b));
    } else if (instruction == "!") {
      this.currStack.push(+!this.currStack.pop());
    } else if (instruction == "?") {
      this.currStack.push(Math.random());
    } else if (instruction == "n") {
      output = "" + this.currStack.pop();
    } else if (instruction == "o") {
      output = String.fromCharCode(this.currStack.pop());
    } else if (instruction == "r") {
      var input = this.program.io.getNumber();
      this.currStack.push(input);
    } else if (instruction == "i") {
      var input = this.program.io.getChar();
      this.currStack.push(input);
    } else if (instruction == "(") {
      this.length -= Math.floor(this.currStack.pop());
      this.length = Math.max(this.length, 0);
    } else if (instruction == ")") {
      this.length += Math.floor(this.currStack.pop());
      this.length = Math.min(this.length, this.code.length);
    } else if (instruction == "w") {
      this.wait = this.currStack.pop();
    }
    // Any instruction not covered by the above cases is ignored
    if (this.ip >= this.length) {
      // We've swallowed the IP, so this snake dies
      this.alive = false;
      this.program.snakesLiving--;
    } else {
      // Increment IP and loop if appropriate
      this.ip = (this.ip + 1) % this.length;
    }
    return output;
  }

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  if (this.snakesLiving) {
    this.step();
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
  for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
}
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}
var ioFunctions = {
  print: function(item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function() {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      return inputChar.charCodeAt(0);
    } else {
      return -1;
    }
  },
  getNumber: function() {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      return +inputNumber;
    } else {
      return -1;
    }
  }
};
var program = null;
var inputData = null;

function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
}

function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  inputData = stdin.value;
}

function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}

function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
.container {
  width: 100%;
}
.so-box {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: bold;
  color: #fff;
  text-align: center;
  padding: .3em .7em;
  font-size: 1em;
  line-height: 1.1;
  border: 1px solid #c47b07;
  -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  background: #f88912;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
  display: inline-block;
  border-radius: 6px;
  float: left;
  margin-right: 25px;
  cursor: pointer;
}
.option {
  padding: 10px 20px;
  margin-right: 25px;
  float: left;
}
h1 {
  text-align: center;
  font-family: Georgia, 'Times New Roman', serif;
}
a {
  text-decoration: none;
}
input,
textarea {
  box-sizing: border-box;
}
textarea {
  display: block;
  white-space: pre;
  overflow: auto;
  height: 40px;
  width: 100%;
  max-width: 100%;
  min-height: 25px;
}
span[contenteditable] {
  padding: 2px 6px;
  background: #cc7801;
  color: #fff;
}
#stdout-container,
#stdin-container {
  height: auto;
  padding: 6px 0;
}
#reset {
  float: right;
}
#source-display-wrapper {
  display: none;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid black;
  box-sizing: border-box;
}
#source-display {
  font-family: monospace;
  white-space: pre;
  padding: 2px;
}
.activeToken {
  background: #f88912;
}
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  display: inline-block;
}
* html .clearfix {
  height: 1%;
}
.clearfix {
  display: block;
}
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">i..96<\64>*32*+m1(
)L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo</textarea>
<div id="source-display-wrapper"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">Testing Testing One Two Three</textarea>
</div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>1000</span></div></div>

DLosc

Posted 2015-10-24T04:47:29.087

Reputation: 21 213

2

C, 60 bytes

n,c,d;main(){for(;read(0,&c-n,1);n=2)d-c&31&&n&&putchar(d);}

Edit: Fixed a bug which caused a null byte to be printed at the beginning

xsot

Posted 2015-10-24T04:47:29.087

Reputation: 5 069

does it even compile ? – Abr001am – 2015-10-26T19:28:13.077

1

Yes. It compiles on my machine (with warnings) and works. You can also test it on this page: http://golf.shinh.org/check.rb

– xsot – 2015-10-26T22:55:22.070

yes it does; +1 – Abr001am – 2015-10-27T11:03:09.707

2

Python 2, 43

lambda s:s.translate(None,(s[0]*2).title())

This is somewhat based on my Pyth answer, but it's also related to some comments from ThomasKwa and xnor from here. Mostly posting because I wanted this answer to exist.

FryAmTheEggman

Posted 2015-10-24T04:47:29.087

Reputation: 16 206

2

Vim, 30 Keystrokes

Sorry to unearth, but i don't see any Vim answer D:

If<Right>xh@x.<Esc>"xy07|@x2|~0"xd7|@x0x

Explanation:

  1. If<Right>xh@x.<Esc>
    Write a (recursive) macro around the first character
    Moving left (h) is needed to stay at the left of the next unread character
    Adding any character (.) at the end is needed in case the second must be removed
  2. "xy0 Copy the macro in the register x
  3. 7| Move to the 7th char
  4. @x Run the macro from x
  5. 2|~ Switch the case of the first char (actually at the 2nd position)
  6. 0"xd7| Cut the macro in the register x
  7. @x Run the macro from x
  8. 0x Remove the place-holder .

user285259

Posted 2015-10-24T04:47:29.087

Reputation: 201

1:D I always upvote vim! – James – 2016-07-27T19:36:56.837

1

Brainfuck, 72 bytes

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

Try it online.

Checks whether the differences between the first character and subsequent characters are divisible by 32.

Mitch Schwartz

Posted 2015-10-24T04:47:29.087

Reputation: 4 899

1

Vim, 11 keystrokes

x:s/<C-r>-//gi

With a trailing newline

Although there already is a Vim answer, this one uses a different approach.

This deletes the first first character, which automatically gets stored in register -. Then we do a search and replace, replacing the deleted character (<C-r>-) with nothing (ie deleting it). The gi flags are used (global and case-insensitive).

user41805

Posted 2015-10-24T04:47:29.087

Reputation: 16 320

1

TeaScript, 16 bytes

TeaScript is JavaScript with shortened property names.

x.g(x[0],'','i')

Try it online


TeaScript 3 came out and now this is 10 bytes.

xg(x░,u,'i

which compiles to:

xg(x[0],u,'i

which compiles to:

x.g(x[0],u,'i')

where u is preset to ""

Downgoat

Posted 2015-10-24T04:47:29.087

Reputation: 27 116

TeaScript does not work for me in firefox. Test aht should be es ah, right? Second (friendly) TeaScript does work. – Zereges – 2015-10-24T06:51:50.367

@Zereges weird. I'll use the other version while I see why that's not working – Downgoat – 2015-10-24T14:52:06.250

1

C++, 100 99 98 bytes

#include<ios>
int main(){for(int c,f=getchar();~(c=getchar());)tolower(c)-tolower(f)&&putchar(c);}

Just one more byte to get under 100. getchar() returns -1 when it reads end of stream, so that's why the ~ is in for cycle. (~-1 == 0)

Ungolfed

#include <ios>
int main()
{
    for (int c, f = getchar(); ~(c = getchar()); )
        tolower(c) - tolower(f) && putchar(c);
}

Zereges

Posted 2015-10-24T04:47:29.087

Reputation: 1 165

Can't you use &&putchar(c) instead of ?putchar(c):0? – Neil – 2015-10-24T15:07:37.720

@Neil Thank you, now I am under 100 bytes! – Zereges – 2015-10-24T15:42:13.703

@ThomasKwa Of course I can, thanks. – Zereges – 2015-10-25T08:12:37.733

1Can you do f-c&31 as in the C answer? – lirtosiast – 2015-10-25T08:17:13.343

1

Haskell, 52 bytes

import Data.Char
t=toUpper
r(h:s)=filter((t h/=).t)s

Leif Willerts

Posted 2015-10-24T04:47:29.087

Reputation: 1 060

2List comprehension saves 1 byte: r(h:s)=[c|c<-s,t c/=t h]. – nimi – 2015-10-24T22:22:48.970

1

C, 65 61 bytes

main(c,v)char**v;{for(c=**++v;*++*v;**v-c&31&&putchar(**v));}

Compiles with warnings. Reads string from argv[1]. Online example

user46060

Posted 2015-10-24T04:47:29.087

Reputation:

1You can shorten main(int c,char**v) to main(c,v)char**v;, and (**v-c)%32 to **v-c&31. – Dennis – 2015-10-25T04:38:11.363

1

TI-BASIC, 164 bytes

For TI-83+/84+ series graphing calculators.

Input Str1
1→X
"sub(Str1,X,1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ zyxwvutsrqponmlkjihgfedcba
u+sub(Ans,54-inString(Ans,u),1
For(X,2,length(Str1
If 2<inString(Ans+Str1,u
Ans+u
End
sub(Ans,3,length(Ans)-2

TI-BASIC is clearly the wrong tool for the job.

  • It doesn't have a command to remove characters, so we need to loop through the string and append characters if they don't match what is to be removed.
  • It doesn't support empty strings, so we need to start the string with the two letters to be removed, build the output onto the end, and chop the first two characters off.
  • It doesn't have case-change commands, so we need to hardcode the entire alphabet...
    • twice...
    • Did I mention lowercase letters take two bytes each in the TI-BASIC encoding?

I'm not 100% sure, but I spent over six hours on this, and it seems to be the shortest possible solution.

To test this with non-uppercase inputs (or to type it into your calculator), make a different program with the contents AsmPrgmFDCB24DEC9, and run it using Asm([whatever you named it] to enable lowercase typing mode.

lirtosiast

Posted 2015-10-24T04:47:29.087

Reputation: 20 331

1

Lua, 93 78 Bytes

a=io.read()m=a:sub(1,1):upper()print(({a:gsub("["..m..m:lower().."]","")})[1])

Digital Veer

Posted 2015-10-24T04:47:29.087

Reputation: 241

1

Common Lisp, 77

(princ(let((x(read-char)))(remove-if(lambda(y)(char-equal x y))(read-line))))

Curse these long function names (and parentheses (but I still love them anyway (:3))).

Candles

Posted 2015-10-24T04:47:29.087

Reputation: 683

1

AppleScript, 209 201 bytes

My only consolation is that I beat Brainfuck.

set a to(display dialog""default answer"")'s text returned
set n to a's characters's number
set o to""
repeat n
if not a's character n=a's character 1 then set o to a's character n&o
set n to n-1
end
o

How this works is that I take input through a, get the length of a and mark it as n, and set an output variable o. For every character that I find that does not contain the first character of a (a's character 1), I concatenate it to o. The final line prints o.

Note: This automatically supports all Unicode. c:

Addison Crump

Posted 2015-10-24T04:47:29.087

Reputation: 10 763

3My only consolation is that I beat Brainfuck. looks like i'd better get golfing ;) – undergroundmonorail – 2015-10-25T15:33:47.380

1

Retina, 16 bytes

i`(.)(?<=^\1.*)

Save the code with a trailing linefeed and run it with the -s flag.

How it works: the trailing linefeed makes this a replacement stage, such that any matches of the given regex are replaced with an empty string. The i turns on case-insensitive mode which also makes backreferences case-insensitive. Finally, the regex simply matches and captures a single characters and then checks whether the first character in the string is the same (up to case) using a backreference.

Martin Ender

Posted 2015-10-24T04:47:29.087

Reputation: 184 808

1

Gema, 19 characters

\A?=@set{c;?}
\C$c=

Sample run:

bash-4.3$ gema '\A?=@set{c;?};\C$c=' <<< 'Testing Testing One Two Three'
esing esing One wo hree

bash-4.3$ gema '\A?=@set{c;?};\C$c=' <<< ' Testing Testing One Two Three'
TestingTestingOneTwoThree

manatwork

Posted 2015-10-24T04:47:29.087

Reputation: 17 865

0

Rebol, 25 bytes

print replace/all s s/1{}

Alternative function at 28 bytes:

func[s][replace/all s s/1{}]

draegtun

Posted 2015-10-24T04:47:29.087

Reputation: 1 592

0

C#, 101 bytes

void m(string s){Console.Write(s.Replace(char.ToUpper(s[0]),'\0').Replace(char.ToLower(s[0]),'\0'));}

Sadly C# falls short on this one due to not having a case insensitivity option in Replace and not having an empty char literal

I tried using regex but it's more bytes (someone might manage shorter with it though)

Alfie Goodacre

Posted 2015-10-24T04:47:29.087

Reputation: 321

0

Java, 96 bytes.

Java is an unlikely winner, it's pretty verbose even in a golfed form. Here |32 is to force lower-case comparison regardless of the actual value, doesn't affect space.

void m(String s){char[]c=s.toCharArray();for(char a:c)System.out.print((a|32)!=(c[0]|32)?a:"");}

At a slightly higher level of String class it would be more explicit (121 bytes):

void m(String s){String f=s.substring(0,1).toLowerCase();System.out.println(s.replaceAll("["+f+f.toUpperCase()+"]",""));}

Andrey

Posted 2015-10-24T04:47:29.087

Reputation: 121

0

Convex, 5 bytes, noncompeting

(_±+-

Try it online!

GamrCorps

Posted 2015-10-24T04:47:29.087

Reputation: 7 058

0

Jelly, 7 6 bytes

żŒsḢ⁸ḟ

Try it online!

1 byte saved thanks to Erik The Outgolfer

How it works

żŒsḢ⁸ḟ - Main link. Argument: s (string) e.g. "ABCabc"

 Œs    - Swap the case                        "abcABC"
ż      - zip with the input                   ["Aa", "Bb", "Cc"]
   Ḣ   - take the first element               "Aa"
     ḟ - Filter those characters from...
    ⁸  -   the input                          "BCbc"

Original

ḟḢ;Œs$$ - Main link. Argument: s (string) e.g. "ABCabc"

 Ḣ      - Generate the first character of s    "A"
   Œs   - Generate the swapped case of ^       "a"
  ;     - Concatenate                          "Aa"
ḟ    $$ - Filter ^ from the input              "BCbc"

caird coinheringaahing

Posted 2015-10-24T04:47:29.087

Reputation: 13 702

Alternatively for 6 bytes: żŒsḢ⁸ḟ – Erik the Outgolfer – 2017-10-17T16:47:02.350

@EriktheOutgolfer oh, nice. Thanks! – caird coinheringaahing – 2017-10-17T16:52:57.243

0

05AB1E, 5 bytes

ćDš«м

Try it online!

Newer version than what Adnan used.

Erik the Outgolfer

Posted 2015-10-24T04:47:29.087

Reputation: 38 134

0

Hassium, 57 Bytes

func main(){s=input().toLower()print(s.replace(s[0],""))}

Run online and see expanded here

Jacob Misirian

Posted 2015-10-24T04:47:29.087

Reputation: 737

4This will change all uppercase letters into lowercase. E.g, the input HEY should be EY but not ey. – Zereges – 2015-10-24T06:48:16.810

0

Julia, 40 bytes

t->t[find([(l=lowercase(t))...].!=l[1])]

l=lowercase(t) makes l store the string t reduced to lowercase. [l...] then converts the string into a character array. .!=l[1] compares that array element-wise with the first value of it, returning true if they don't match. find then converts the resulting boolean array into an array containing the true indices, and t[] then returns the desired string.

It feels like Julia should be able to do better than this, but so far I can't see it. It's a lot easier if you don't have to catch both upper- and lower-case instances of the letter.

Glen O

Posted 2015-10-24T04:47:29.087

Reputation: 2 548

0

Ceylon, 93 84

String r(String i)=>String{if(exists f=i[0])for(c in i.rest)if(c.offset(f)%32!=0)c};

This defines a function r which takes and returns a String, solving the task.

Formatted:

String r(String i) =>
        String {
    if (exists f = i[0])
        for (c in i.rest)
            if (c.offset(f) % 32 != 0)
                c };

The function creates and returns a string from an Iterable comprehension, composed of several if- and for-clauses.

The first if makes sure that the string is non-empty (if its empty, the iterable will be empty, thus the returned string too), and at the same time declares the f variable to be used later. (i[0] could have also been written i.first, but this way is shorter.) While the question says we can be sure the input has always length > 1, the compiler doesn't know this. (A different way of saying this would be to use an assert statement, but this would be even longer.)

The next for clause iterates over the remainder of the string (i.e. the string without its first character). Each item is named c.

The second if does the case-check. It turns out that in ASCII, the upper- and lower case letters have distance 32 from each other, so c.offset(f) % 32 != 0 is a slightly shorter way of writing c.uppercased != f.uppercased. (This would also filter other character, e.g. in the input strings Testing Testing One Two Three4, Programming Puzzles and 0Code0 Golf00, ((((How much wood would (a( woodchuck chuck (if a woodchuck could chuck (wood, @ hello` `world, 7welcome to WATER WORLD7 would also result in the example outputs in the question. But as the input is restricted to [A-Z a-z]+, we don't care.)

The last clause it simply the expression c – which will be included if the if clause's condition is true, and omitted otherwise.

The resulting iterable is passed to the String's class constructor, which iterates over it and creates the string.

As a bonus, here is a version which works for all of unicode:

String r(String i) =>
        String {
    if (exists f = i[0])
        for (c in i.rest)
            if (c.uppercased != f.uppercased)
                c };

After space-removal this is 93 bytes:

String r(String i)=>String{if(exists f=i[0])for(c in i.rest)if(c.uppercased!=f.uppercased)c};

It converts (beside the example phrases) also Übel wütet der Gürtelwürger to bel wtet der Grtelwrger.

Paŭlo Ebermann

Posted 2015-10-24T04:47:29.087

Reputation: 1 010

0

Simplex v.0.6, 10 bytes

bC&0/gi//g
b          ~~ takes input as a string
 C  /  //  ~~ match as SiRegex
  &0       ~~ replace the first cell
     gi    ~~ globally, ignoring case,
           ~~ with the empty string
         g ~~ output the result

No regrets about adding a new type of Regular Expression. (SiRegex FTW!)

Conor O'Brien

Posted 2015-10-24T04:47:29.087

Reputation: 36 228

0

Bash, 35 characters

c=${1::1}
echo "${1//[${c^}${c,}]}"

Sample run:

bash-4.3$ bash rm-1st-char.sh 'Testing Testing One Two Three'
esing esing One wo hree

bash-4.3$ bash rm-1st-char.sh ' Testing Testing One Two Three'
TestingTestingOneTwoThree

manatwork

Posted 2015-10-24T04:47:29.087

Reputation: 17 865

0

C(136)

#define t(x)(x+32*(x>>5==2)) 
char*h(char*a,int b,int*c){char*v=a[b+1]?h(a,b+1,c):0;return(b<=*c)?v:&(a[b]=a[b-(*c+=t(*a)==t(a[b]))]);}

Execution

void main(){

    char a[]="abac";int v=0;
    printf("%s",h((char*)a,0,&v));
    return;
}

Output

bc

  • the function is recursive which is called from the initial parameters: h(string,0,0) and returns the beginning of the resulting string.

Abr001am

Posted 2015-10-24T04:47:29.087

Reputation: 862

0

How about a Nodejs RegEx?

My answer is 60 bytes. Without all the function wrapper stuff it could be as little as 35 bytes. The function called 'lop()' could even be one character name like 'x()' or something, making it 58 bytes.

Answer

function lop(s){return s.replace(new RegExp(s[0],'gi'),'');}
or
s.replace(new RegExp(s[0],'gi'),'')  

Test Code

function test(s)  
{  
    console.log();  
    console.log('> ' + s);  
    console.log('< ' + lop(s));  
}  

// **test data**  
test("Testing Testing One Two Three");  
test("Programming Puzzles and Code Golf");  
test("How much wood would a woodchuck chuck if a woodchuck could chuck wood");  
test(" hello world");  
test("welcome to WATER WORLD");  
test("A welcome to WATER WORLD");  
test("A first test of a solid A remover.");  

Output

> Testing Testing One Two Three
< esing esing One wo hree

> Programming Puzzles and Code Golf
< rogramming uzzles and Code Golf

> How much wood would a woodchuck chuck if a woodchuck could chuck wood
< ow muc wood would a woodcuck cuck if a woodcuck could cuck wood

>  hello world
< helloworld

> welcome to WATER WORLD
< elcome to ATER ORLD

> A welcome to WATER WORLD
<  welcome to WTER WORLD

> A first test of a solid A remover.
<  first test of  solid  remover. 

Scott

Posted 2015-10-24T04:47:29.087

Reputation: 1

1You should aim to reduce your code as much as possible. This is [tag:code-golf], so answering as minimally as possible is the name of the game. Also, for code blocks, use the <pre> html tag. If you include test data, make sure you put the actual output of the code in as well. – Addison Crump – 2015-10-27T01:53:39.613

Please also make the first line of your program a heading with the language used and the number of bytes. – lirtosiast – 2015-10-29T01:59:36.437

0

Powershell, 62 60 44 bytes

$args-replace"$($args.substring(0,1))",""

Powershell of all things.

Edit: removed whitespace to save 2 bytes
Edit2: removed type accelerators to save 16 more bytes

Xalorous

Posted 2015-10-24T04:47:29.087

Reputation: 111

2Hi and welcome to Programming Puzzles and Code Golf Stack Exchange (PPCG.SE for short)! Just FYI, the standard format of an answer starts with #[Language], [N] bytes as the first line where N is the length (in UTF-8 bytes) of your program. Otherwise, I, along with the rest of the PPCG.SE community wishes you good luck in your golfing adventure! – GamrCorps – 2015-10-28T03:38:12.350

Thanks for the welcome and the advice. You barely beat the downvotes. Gotta love SE.

I've been struggling to use regex instead of .net string handling, thinking it would save me some bytes, however, I can't seem to find a way to capture the first character AND search for it using $string.replace("...","") – Xalorous – 2015-10-28T04:02:48.743

Can be further shortened to $argz-replace($argz[0]) (23 bytes). – beatcracker – 2017-10-18T00:43:41.787

0

, 6 chars / 13 bytes (non-competitive)

ïĥ/⏖î⍀

Try it here (Firefox only).

As does happen a lot, I beat everyone in char count but not in byte count :P

Explanation

ï is input, ĥ is replace, /...⍀ transpiles to /.../gi in JS, and ⏖î directly replaces the result of ï[0] in the compiled code.

Mama Fun Roll

Posted 2015-10-24T04:47:29.087

Reputation: 7 234

0

05AB1E, 7 Bytes

¬DŠ-sš-

Explanation:

¬        # Take the first character of the input
 D       # Duplicate top of the stack
  Š      # Pop a,b,c and push c,a,b
   -     # Remove all occurencies of the first letter
    s    # Swap the two top elements
     š   # Swapcase the top of the stack
      -  # Remove all occurencies of the swapcased letter
         # Implicit: print top of the stack

Uses ISO 8859-1 encoding

Adnan

Posted 2015-10-24T04:47:29.087

Reputation: 41 965

¬Dš‚K is 5, AFAICT. – Magic Octopus Urn – 2017-10-17T17:14:20.180

0

Common Lisp, 47 bytes

(lambda(s)(remove(aref s 0)s :test'char-equal))

coredump

Posted 2015-10-24T04:47:29.087

Reputation: 6 292

0

J, 17 bytes

#~1-(={.)@tolower

Usage

   f =: #~1-(={.)@tolower
   f 'Testing Testing One Two Three'
esing esing One wo hree
   f 'Programming Puzzles and Code Golf'
rogramming uzzles and Code Golf
   f ' hello world'
helloworld

miles

Posted 2015-10-24T04:47:29.087

Reputation: 15 654