title: Animate the text in your terminal

text:
# Question
Title: Animate the text in your terminal
## Animate the text in your terminal

**The goal**

The goal is to "animate" the string "Hello world" in your output so that each character gets capitalised after each other.

Your program can exit after each letter has been capitalised.

For example;

```
# Iteration 1
Hello world

# Iteration 2
hEllo world

# Iteration 3
heLlo world

# Iteration 4
helLo world

# Iteration 5
hellO world

# Iteration 6 (note: it should capitilize the space char (ie: a break between iteration 5 and iteration 7)
hello world

# Iteration 7
hello World

# Iteration 8
hello wOrld

# Iteration 9
hello woRld

# Iteration 10
hello worLd

# Iteration 11
hello worlD

```

It should only animate the string once and between each state there should be a 1 second delay.

**Input**

No input is required, but "Hello world" must be the string that is "animated".

**Output**

The string "Hello world" must be animated. The output must be as 1 line to create a sort of wave animation. An empty trailing new line is allowed. Example gif;

I saw this on a metasploit youtube video and thought the effect was pretty cool, which is where I recorded the gif from, so it's a little laggy, but I hope it illustrates the output fine

This is , lowest byte-count will be deemed the winner.

Sandbox Link

# Answer
# Vim 26 bytes

```
ihello world<ESC>qq~gsul@qq0@q

```

Explanation (no .gif yet):

First, we must enter the 'hello world' text. This is pretty straightforward. It's just:

```
ihello world<ESC>

```

At this point, the cursor is on the 'd' in 'world'. Next:

```
qq              " Start recording into register 'q'
  ~             " Swap the case of the character underneath the cursor, and move the cursor to the right
   gs           " Sleep for one second
     u          " Undo the last change (of swapping case).
      l         " Move one character to the right (Get it? 'l' == 'Right' because vim is intuitive!)
                " This will cause the error to break on the last character of the input.
       @q       " Call register 'q'
         q      " Stop recording
          0     " Move to the first character
           @q   " Call the recursive macro

```

There are also two other 26 byte versions I found:

```
ihello world<ESC>qq~gsulq011@q
ihello world<ESC>011@='~gsul'<cr>

```
> 34 votes

# Answer
# Python 2, ~~98~~ ~~94~~ 90 bytes

```
for x in range(11):s='hello world';print'\r'+s[:x]+s[x:].capitalize(),;[1for y in' '*8**8]

```

~~-9~~ -4 bytes thanks to @ElPedro -4 bytes thanks to @JonathanAllan and @Rod
> 15 votes

# Answer
# Commodore 64, 168 162 137 133 BASIC (and tokenized) bytes used

```
 0s=1024:?"{control+n}{clear home}hello world":fOi=.to1:fOj=.to11:x=pE(s+j):pokes+j,x+64
 1x=pE(1023+j):pO1023+j,abs(x-64):pO1029,32:pO1035,32:fOz=.to99:i=.:nEz,j,i

```

You will need to use BASIC keyword abbreviations to enter this into a real C64 or emulator (or enter the program into a Commodore 128 and load it back in C64 mode, although this should work on the 128 as well). The `{control+n}` will only work/display after the opening quote. It is shorthand for `chr$(14)` and therefore saves some bytes and switches the character set to *business mode* or upper/lower case characters.

I have added in some abbreviations for you so you. The `{clear home}` character is made by pressing `Shift` and the `CLR/HOME` key after the opening quotation mark.

For illustrative purposes the unobfustcated listing may be entered as follows:

```
 0 let s=1024
 1 print chr$(14); chr$(147); "hello world"
 2 for i=0 to 1
 3  for j=0 to 11
 4   let x=peek(s + j)
 5   poke s + j, x + 64
 6   let x=peek(1023 + j)
 7   poke 1023 + j, abs(x - 64)
 8   poke 1029, 32
 9   poke 1035, 32
10   for z=0 to 99
11    let i=0
12   next z
13  next j
14 next i

```

It works by switching the PETSCII charset into business mode (upper/lower case), and writing the hello world string to the top line of the screen which is located at memory location $0400, it will then take the value at each location for the next 11 bytes from there and increase each value by 64 (the upper case equivalent). If the j counter is \> 0, it calls a routine at line 2 to decrease the previous memory location by 64 again.

Line 3 is a pause, it also writes a space to to location $0405 and $040b, which is a bug fix (which could probably be removed to save some bytes).
> 12 votes

# Answer
# C#, ~~230~~ ~~215~~ ~~193~~ ~~161~~ ~~135~~ ~~134~~ 130 bytes

It's C# so it's long right! :-( But after some help and searching, I (and others, really) managed to remove exactly 100 bytes already.

## Golfed

```
()=>{for(int i=1;;){var b="\rhello world".ToCharArray();b[i++]-=' ';System.Console.Write(b);System.Threading.Thread.Sleep(1000);}}

```

## Ungolfed

```
class P
{
    static void Main()
    {
        for (int i = 1;;)
        {
            var b = "\rhello world".ToCharArray();
            b[i++] -= ' ';
            System.Console.Write(b);
            System.Threading.Thread.Sleep(1000);
        }
    }
}

```

### Screenshot

Although it looks alot better when looping and faster..

### Updates

* Lost 15 bytes by using carriage return instead of `Clear()` which also allowed me to replace a using with `System.Console`somewhere inline.
* Replaced program with lambda saving 23 bytes thanks to **@devRicher**
* It became kind of a collaboration with **@devRicher** at this point, thanks to some of his suggestions I managed to lose another 32 bytes!
* Thanks to 2 really smart and interesting suggestions by **@Kratz** I managed to replace `new string(b)` with `b` and `b[i]=char.ToUpper(b[i])` with `b[i]-=' '`, saving me another 26 bytes!
* 1 byte less by moving `i++` thanks to **@Snowfire**
* 4 bytes less by moving carriage return to the beginning of the string and removing `i<11` from my `for` loop
> 11 votes

# Answer
# Powershell, ~~126~~ ~~119~~ ~~107~~ 104 Bytes

```
'Hello world';$s='hello world';1..10|%{sleep 1;cls;-join($s[0..($_-1)]+[char]($s[$_]-32)+$s[++$_..11])}

```

Revisions (there will likely be many):

Change `$s.Length` to const ~~`10`~~ 11

Restructured string builder, removed 1 join statement and used `++$s` instead of `($s+1)`, to save some bytes thanks to @AdmBorkBork

AdmBorkBork points out just using the string twice is actually shorter than encapsulating and then `.ToLower()`'ing it - which says a lot about how verbose powershell is, -3!

---

basically loop through the length of the string, form an array of three parts, the pre-capitcal, capital, and post-capital, take 32 away from the middle letter, then convert back to a char to get upper case, luckily this doesn't turn space into a visible character either, I hope this is acceptable?
> 11 votes

# Answer
## CP-1610 assembly, 50 DECLEs = 63 bytes

This code is intended to be run on an Intellivision.

A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This program is 50 DECLEs long, starting at $4800 and ending at $4831.

```
                                  ROMW  10          ; use 10-bit ROM
                                  ORG   $4800       ; start program at address $4800

                          main    PROC
4800 0002                         EIS               ; enable interrupts (to enable display)

4801 0001                         SDBD              ; load pointer to string in R4
4802 02BC 0026 0048               MVII  #@@str, R4

4805 02A2                         MVI@  R4,     R2  ; R2 = length of string
4806 0091                         MOVR  R2,     R1  ; R1 = uppercase counter

4807 02BD 0214            @@loop  MVII  #$214,  R5  ; R5 = video memory pointer
4809 0093                         MOVR  R2,     R3  ; R3 = character counter

480A 02A0                 @@next  MVI@  R4,     R0  ; R0 = next character
480B 0338 0020                    SUBI  #32,    R0  ; minus 32 -> character #
480D 004C                         SLL   R0,     2   ; multiply by 8 to get the
480E 0048                         SLL   R0          ; correct GROM card
480F 03F8 0007                    XORI  #7,     R0  ; add 7 (for white)

4811 014B                         CMPR  R1,     R3  ; uppercase? ...
4812 020C 0002                    BNEQ  @@draw

4814 0338 0100                    SUBI  #256,   R0  ; ... yes: sub 32*8

4816 0268                 @@draw  MVO@  R0,     R5  ; draw character
4817 0013                         DECR  R3          ; decrement character counter
4818 022C 000F                    BNEQ  @@next      ; process next character or stop

481A 0001                         SDBD              ; R0 = spin counter to wait ~1 second
481B 02B8 0038 00D3               MVII  #$D338, R0  ;    = 54072 = 13518 * 60 / 15
                                                    ; (assuming 13518 cycles per frame)

481E 0010                 @@spin  DECR  R0          ; 6 cycles
481F 022C 0002                    BNEQ  @@spin      ; 9 cycles
                                                    ; -> 15 cycles per iteration

4821 0114                         SUBR  R2,     R4  ; reset pointer to beginning of string
4822 0011                         DECR  R1          ; decrement uppercase counter
4823 022C 001D                    BNEQ  @@loop      ; process next iteration or stop

4825 0017                         DECR  PC          ; infinite loop

4826 000B 0068 0065 006C  @@str   STRING 11, "hello world"
482A 006C 006F 0020 0077
482E 006F 0072 006C 0064
                                  ENDP

```

### Output
> 9 votes

# Answer
# MATL, 30 bytes

```
11:"10&Xx'hello world't@)Xk@(D

```

Try it at MATL Online!

```
11:              % Push [1 2 ... 11]
  "              % For each k in [1 2 ... 11]
  10&Xx          %   Pause for 10 tenths of a second and clear screen
  'hello world'  %   Push this string
  t              %   Duplicate
  @)             %   Get the k-th character from the duplicated string
  Xk             %   Convert to uppercase
  @(             %   Write into the k-th position of the string
  D              %   Display
                 % Implicit end

```
> 7 votes

# Answer
# PHP, ~~76~~ ~~74~~ 71 bytes

Thank you @hd for the delay being a full second and no fraction thereof!
Thanks @user63956 for 2 bytes and @aross for 3 bytes.

```
for(;$c=($s="hello world")[$i];sleep(print"$s\r"))$s[$i++]=ucfirst($c);

```

Run with `-nr`.
> 5 votes

# Answer
# C, ~~97~~ ~~withdrawn~~ 106 bytes

with escaped characters counted as 1 byte

```
char*a="HELLO\0WORLD\xED";b,c;m(){for(b=0;b<156;putchar(a[c]+32*(b/12^c||c==5)))(c=b++%12)||fflush(sleep(1));}

```

Note: I have ~~commented out the time delay on~~ unlinked TIO because it waits for completion before displaying the output, it also doesn't seem to recognize carriage returns and puts new lines. Also, if you're on Windows, sleep is in milliseconds instead of seconds, so `sleep(1)` should become `sleep(1000)`.

~~Note 2: I've withdrawn this entry for the moment until the output bugs have been ironed out.~~
> 4 votes

# Answer
# JavaScript (ES6), ~~141 139~~ 131 bytes

*Saved 8B thanks to Apsillers*

```
_=>a=setInterval("b=[...`hello world`],c.clear(b[d]=b[d].toUpperCase(++d>10&&clearInterval(a))),c.log(b.join``)",1e3,c=console,d=0)

```

# Explanation

This creates a function with no arguments, which splits the string `hello world` into an array of characters and capitalises the `d+1`th character. `d` is a counter that starts as `0` and is increased every time.

# Usage

```
f=_=>a=setInterval("b=[...`hello world`],c.clear(b[d]=b[d].toUpperCase(++d>10&&clearInterval(a))),c.log(b.join``)",1e3,c=console,d=0)
f()

```
> 4 votes

# Answer
# Noodel, 22 bytes

```
”<8@\|DḶ|\6þıHḶƥɲSḍsɲS

```

Try it:)

---

# How it works

```
”<8@\|DḶ|\6þ           # Displays the string "hello¤world".
”<8@\|DḶ|\6            # Decompresses to the array ["h", "e", "l", "l", "o", "¤", "w", "o", "r", "l", "d"] and pushes it on top of the stack.
           þ           # Pushes a copy of the array to the screen which since is an array is done by reference.

            ı          # Makes the array on the top of the stack the new stack.

             HḶƥɲSḍsɲS # Loops eleven times creating the animation.
             H         # Pushes the string "H" on to the top of the stack.
              Ḷ        # Consumes the "H" that gets evaluated as a base 98 number which comes out to eleven.
               ƥ       # Move the stack pointer up one.
                ɲS     # Switch the case of the top of the stack which will show up on the screen because the array is done by reference.
                  ḍs   # Delay for one second.
                    ɲS # Switch the case back.
                       # Implicit end of the loop.

```

---

The snippet uses a **25 byte** version that loops continuously.

```
<div id="noodel" cols="10" rows="2" code="”<8@\|DḶ|\6þıḷʠ*HḶƥɲSḍsɲS" input=""/>
<script src="https://tkellehe.github.io/noodel/release/noodel-2.5.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 4 votes

# Answer
# Bash + coreutils, ~~99~~ 98 bytes

```
x=hello\ world
for((;n<11;)){
echo -en "\r${x:0:n}"`tr a-z A-Z<<<"${x:n:1}"`"${x:n+++1}"
sleep 1
}

```
> 4 votes

# Answer
# Perl 6, ~~65~~ 61 bytes

~~```
for 3..12 ->\i{sleep say "\echello world".&{S:nth(i)/./{$/.uc}/}}

```~~
```
(sleep say S:nth(3+$++)/./{$/.uc}/with "\echello world")xx 11

```

GIF:

### How it works

The ANSI escape sequence `\ec` clears the screen.
Each iteration, the `i`'th character of the hard-coded string is substituted by its upper-case version.
The `say` function always returns `True`, which is passed on to the sleep function which interprets it as `1` second.
> 3 votes

# Answer
## Ruby, ~~82~~ 81 bytes

```
12.times{|a|$><<?^H*11;'Hello world'.chars{|y|$><<((0!=a-=1)?y:y.upcase)};sleep 1}

```

^H is ascii 8 (backspace), and is only 1 byte.
> 3 votes

# Answer
# C, 87 bytes

```
m(){char*f,a[]="\rhello world";for(f=a;*++f;*f&=95,printf(a),*f|=32,fflush(sleep(1)));}

```

Compiles and runs on Linux.
> 3 votes

# Answer
# , ~~106~~ 103 bytes

```
x=el(strsplit("hello world",""))
for(i in 1:11){y=x;y[i]=toupper(y[i]);cat('\f',y,sep='');Sys.sleep(1)}

```

Just a simple loop, clearing the console with `cat('\f')` seems somewhat system-dependent but I am not aware of a better way.
> 3 votes

# Answer
# Mathematica, ~~130~~ ~~128~~ ~~123~~ ~~110~~ 108 bytes

```
Dynamic@o
s="hello world";i=1;t=StringTake;Do[o=t[s,{1,i-1}]<>Capitalize@t[s,{i}]<>t[s,{++i,11}];Pause@1,11]

```

Explanation: From `i=1` to 11, print from the 1st to the (i-1)th character of "hello world", capitalise `"hello world"[i]`, then print the rest of the string, incrementing `i` at the same time.
> 3 votes

# Answer
# Java ~~215~~ ~~212~~ ~~204~~ 203 bytes

```
interface A{static void main(String z[])throws Exception{for(int i=0;i<10;i++){char[]b="helloworld".toCharArray();b[i]=Character.toUpperCase(b[i]);System.out.println(new String(b));Thread.sleep(1000);}}}

```

Ungolfed:

```
 interface A {
 static void main(String z[]) throws Exception {
    for (int i = 0; i < 10; i++) {
        char[] b = "helloworld".toCharArray();
        b[i] = Character.toUpperCase(b[i]);
        System.out.println(new String(b));
        Thread.sleep(1000);
    }
  }
}

```
> 3 votes

# Answer
# C, 122 bytes

```
i;f(){char s[]="Hello world\r";for(i=0;i<11;i++){s[i]=toupper(s[i]);s[i-1]=tolower(s[i-1]);printf(s);fflush(0);sleep(1);}}

```

Shorter than C# :D
> 2 votes

# Answer
# Perl, 75 bytes

```
sleep print"\33c".("hello world"=~s/(.{$_})(.)(.*)/$1\U$2\E$3\n/r)for 0..10

```

Uses the ANSI code `ESC``c` to clear the console and move the cursor to the top left at every iteration, but still needs `\n` at the end of the replace string to avoid having the whole animation lost in the line buffer.

A successful call to `print` returns a value of 1, which can be passed directly to `sleep`.
> 2 votes

# Answer
## C ~~120~~ ~~110~~ ~~104~~ 96 bytes

```
f(){char *j,s[]="\rhello world";for(j=s;*++j;*j-=32,printf(s),*j+=32,fflush(0),sleep(1));}

```

Ungolfed version

```
void f()
{
  char *j;
  char s[]="hello world";
  j=s;

   for (;*j;j++)
   {
      *j-=32;
       printf(s); // print the string and right after change the same char to lower case
       *j+=32;
      fflush(0);
      sleep(1);
   }

}

```

@Pakk Thanks for saving some bytes, great idea. :)

@Pakk @KarlNapf Thanks guys for your inputs.

can still be shortened!? :)
> 2 votes

# Answer
# Pascal, ~~187~~ 152 bytes

Not exactly the most efficient or the shortest, but works quite well!

```
uses crt,sysutils;label R;const X:Word=1;P='hello world';begin
R:clrscr;write(P);gotoxy(X,1);write(upcase(P[X]));sleep(999);X:=X*Ord(X<11)+1;goto R
end.

```

Tested and works on Free Pascal Compiler 2.6+.

Thanks to @manatwork for saving **35** bytes!

---

I've used http://www.onlinecompiler.net/pascal to compile the file and run it on Windows.
Haven't seen any problem with it, so far.
> 2 votes

# Answer
# SmileBASIC, ~~90~~ 71 bytes

```
FOR I=0TO 10CLS?"hello world
LOCATE I,0?CHR$(CHKCHR(I,0)-32)WAIT 60NEXT

```
> 2 votes

# Answer
# Jelly, ~~24~~ 21 bytes

```
”Æ⁹Œu⁸¦ȮœS
“½,⁻⁸3»Jç€

```

This is a niladic link/function that prints to STDOUT. It does not work as a full program.

The code can't be tested on TIO; it uses control characters and TIO has no terminal emulator (yet).

### How it works

```
“½,⁻⁸3»Jç€  Niladic link. No arguments.

“½,⁻⁸3»     Index into Jelly's dictionary to yield "hello world".
       J    Indices; yield [1, ..., 11].
        ç€  Apply the helper link to each index, with right arg. "hello world".

”Æ⁹Œu⁸¦ȮœS  Dyadic helper link. Left argument: i. Right argument: "hello world"

”Æ          Set the return value to '\r'.
  ⁹         Set the return value to "hello world". Implicitly prints '\r'.
   Œu⁸¦     Uppercase the i-th letter.
       Ȯ    Print.
        œS  Sleep "hello world" seconds. (Strings are cast to Boolean.)

```
> 2 votes

# Answer
# C, 122 bytes

As an exercise, I wrote this to provide a more optimal output format than some of the other answers. Also it means the cursor sits after the most recently capitalized letter during the pauses.

```
main(){
    char*p=".Hello world\rH";
    write(1,p+1,13);
    do{
        sleep(1);
        *p=8;
        p[1]|=32;
        p[2]^=(p[2]>32)*32;
        write(1,p++,3);
    }while(p[4]);
}

```

(Newlines and indentations cosmetic and not part of byte count)

Now, some readers may note that this requires some massaging to get to run on modern machines (the magic incantation is `-static -Wl,-N`), but this is how real implementations of C used to behave, so I think it is valid. It also assumes the character set is ASCII, and it does not print a trailing newline.

Bonus: For an EBCDIC version, you can replace `8` with `22` and `64` with `32`, and switch the logic for `p[1]` and `p[2]`. To test on a non-EBCDIC system, you can compile with `-funsigned-char -fexec-charset=cp037`.

Output is 43 bytes: `Hello world«H‹hE‹eL‹lL‹lO‹o ‹ W‹wO‹oR‹rL‹lD`
> 2 votes

# Answer
# Scala, 92 bytes

```
val h="hello world"
0 to 10 map{i=>print("\b"*99+h.updated(i,h(i)toUpper))
Thread sleep 999}

```

## Ungolfed

```
val h="hello world"    //declare a variable h with the string "hello world"
0 to 10                //create a range from 0 to 10
map { i=>              //loop with index i
  print(                 //print
    "\b" * 99              //99 backspace chars
    + h.updated(           //and h with
      i,                     //the i-th char
      h(i).toUpper           //replaced with the i-th char in uppercase
    )
  )
  Thread sleep 999       //sleep 999 ms
}

```
> 2 votes

# Answer
# Clojure, 116 bytes

```
(doseq[i(range 11)](Thread/sleep 1000)(print"\r"(apply str(update(vec"hello world")i #(char(-(int %) 32)))))(flush))

```

Basically a for-loop that goes over the indices of each character, updating each character in turn.

```
(defn -main []
  (doseq [i (range 11)] ; For the index of each character...
    (Thread/sleep 1000)
    (print "\r" ; Clear old line
           (apply str ; Turn the vector back into a string
             (update ; Update the char at index i
               (vec "hello world") ; Turn the string into a vector so it's updatable
               i ; Index to update
               #(char (- (int %) 32))))) ; Subtract 32 from the character to make uppercase
    (flush)))

```
> 2 votes

# Answer
## Batch, 184 bytes

```
@echo off
for %%h in (Hello hEllo heLlo helLo hellO hello)do call:c %%h world
for %%w in (World wOrld woRld worLd worlD)do call:c hello %%w
exit/b
:c
timeout/t>nul 1
cls
echo %*

```

Curiously the command line for `timeout/t>nul 1` gets corrupted if there is no trailing newline, so I can't put it at the end of the file.
> 2 votes

# Answer
## Python 2, ~~220~~ ~~189~~ 179 bytes

Solution without using strings and `capitalize()`, byte count as is:

```
import time,sys
from numpy import *
F=fromstring("\rhello world",int8)
for i in range(1,12):
    time.sleep(1)
    F[i]-=32
    savetxt(sys.stdout,F,fmt="%c",newline="")
    F[i]+=32

```

And a bit longer variant (191 chars) without case resetting:

```
import time,sys
from numpy import *
a=arange(11)
F=tile(fromstring("\rhello world",int8),(11,1))
F[a,a+1]-=32
for i in a:
    time.sleep(1)
    savetxt(sys.stdout,F[i],fmt="%c",newline="")

```
> 2 votes

# Answer
# Ruby, 108 bytes

First time, first year student. It's no eagle but I'm at least a little proud.

```
12.times{|i|sleep(0.1); puts "\e[H\e[2J", "hello world".sub(/(?<=.{#{Regexp.quote(i.to_s)}})./, &:upcase);}

```
> 2 votes

# Answer
## C++, 88 125 Bytes

```
#include<iostream>#include<unistd.h>
int main(){for(int c;++c<12;){char a[]="\rhello world";a[c]-=32;std::cout<<a;sleep(1);}}

```

Ungolfed version:

```
#include <iostream>
#include <unistd.h>

int main()
{
   for (int c;++c<12;)
   {
      char a[] = "\rhello world";
      a[c]-=32;
      std::cout << a;
      sleep(1);
   }
}

```

Compiled with TDM-GCC on a Windows 10 machine with Dev-C++.

Edit: I forgot the includes in my first version.
> 2 votes

# Answer
# Linux C, 180 bytes code, 6336 bytes binary (gcc+strip x86\_64)

```
#include<unistd.h>
char s[]="\rhello world";
int main(){int n;for(n=1;s[n]!=0;n++){if(s[n]>0x40)s[n]^=0x20;if(n>1)if(s[n-1]>0x40)s[n-1]^=0x20;write(1,&s,sizeof(s)-1);sleep(1);};};

```
> 2 votes

# Answer
## AWK, 123 bytes

```
BEGIN{s="hello world\n"
split(s,a,"")
for(L=1;L<12;L++){for(m=1;m<13;m++)printf m==L?toupper(a[m]):a[m]
system("sleep 1")}}

```

Fairly standard `AWK` but it does require the availability of `sleep`. On my `Linux` box the default argument to `sleep` is an integer number of seconds.
> 2 votes

# Answer
# Java, 137 bytes

```
String q="HELLO WORLD";for(int x,i=0;i<132;System.out.print((char)(x>10?10:(x!=i/12?32:0)|q.charAt(x))))Thread.sleep((x=i++%12)<1?999:0);

```

Ungolfed and with comments:

```
    String q = "HELLO WORLD"; // note that the string is 11 characters long
    for (int x, i = 0;
         i < 132; // 11 rows, 12 columns (one column for newlines)
         System.out.print((char) (x > 10 ? // if this is the last column
                 10 // print newline
                 : // else:
                 (x != i / 12 ? //check if column == row
                         32 : 0) | q.charAt(x)))) // de-capitalize
        Thread.sleep((x = i++ % 12) < 1 ? 999 : 0); // if this is the first column, wait almost 1 second.
    // the above line will also update i and x

```

Edit: A full program would take 196 bytes
> 2 votes

# Answer
# Common Lisp, 108 bytes

```
(let((a"hello world"))(dotimes(i 11)(format t"~a~c"(string-upcase a :start i :end(1+ i))#\return)(sleep 1)))

```

Works on a regular terminal, on tio.run does not overwrite the string.
> 2 votes

# Answer
# PowerShell 3.0, ~~72~~ 63 Bytes

-9 bytes thanks to mazzy

```
0..10|%{cls;($s=[char[]]'hello world')[$_]-=32;-join$s;sleep 1}

```

Not too shabby.
> 2 votes

# Answer
**Haskell** ~~**232**~~ **212** **Bytes**

The trickiest part was reliably implementing a delay using prelude. Control.Concurrent threadDelay could be used for a robust solution. I started with `delay n= foldr seq "\&" (drop n[5.5*10^6..10^7]` which works in the REPL, however does not work compiled into a .exe.

Golfed Version

```
d=[0..10]>>"\BS"
p=concat$replicate(2*10^5)" \BS"
l=zip['a'..'z']['A'..'Z']
t x=([u|(l,u)<-l,l==x]++" ")!!0
y(x:xs)e|length xs==12-e=t x:xs|1>0=x:(y xs e)
main = do mapM_ putStr$[y"hello world"x++p++d|x<-[2..12]]

```

Explanation:

```
--Create a row of backspaces. When sent to IO deletes last character
delrow= [0..10]>>"\BS"

--print beaucoup spaces and backspaces
printblank = concat $ replicate (200000)  (' ':"\BS")

--Helpers to create a caps letter
lowerandupper = zip (['a'..'z']) (['A'..'Z'])
toupper x = head ([u|(l,u)<-lowerandupper, l==x]++" ")
touppers (x:xs) elem | length xs == 12- elem = toupper x :xs
                   | 1>0 = x: (touppers xs elem)

main = do
        --use mapM_ to putStr for each element of list
        mapM_ putStr $ [touppers "hello world" x ++ printblank++delrow|x <-[2..12]]

```

Looking forward to comments, feedback and improvements.

@laikoni thanks for the inputs saving numerous bytes.
> 1 votes

# Answer
# Rebol, 70 bytes

```
repeat n 11[prin[head uppercase/part at copy"hello world^M"n 1]wait 1]

```

Ungolfed:

```
repeat n 11 [
    prin [head uppercase/part at copy "hello world^M" n 1]
    wait 1
]

```
> 1 votes

# Answer
# Java - 240 bytes

```
interface a{static void main(String[]a)throws Throwable{int x=1;char[]b="\rhello world".toCharArray();while(x<12){if(b[x]!=' ')b[x]=(char)((int)b[x]^32);System.out.print(b);Thread.sleep(1000);if(b[x]!=' ')b[x]=(char)((int)b[x]^32);x++;}}}

```

Ungolfed version:

```
interface a {
    static void main(String[] a) throws Throwable {
        int x = 1;
        char[] b = "\rhello world".toCharArray();
        while(x < 12) {
            if (b[x] != ' ')
                b[x]=(char)((int)b[x]^32);
            System.out.print(b);
            Thread.sleep(1000);
            if (b[x] != ' ')
                b[x]=(char)((int)b[x]^32);
            x++;
        }
    }
}

```
> 1 votes

# Answer
# Scala, 139 Bytes

```
() => {
    val a = "\033[H\033[2J\nhello world"
    8 to 19 map{c=>
        print(a.updated(c,a(c)toUpper))
        Thread.sleep(1000)
    }
}

```
> 1 votes

# Answer
# C (MinGW), ~~83~~ ~~80~~ 77 bytes

Only tested on Windows.

`f(){for(char s[]="\rhello world",*t=s;*++t;*t+=32)*t-=32,printf(s),sleep(1);}`
> 1 votes

# Answer
# Ruby, 56 bytes

```
"hello world".gsub(/./){$><<?\r+$`+$&.upcase+$'
sleep 1}

```
> 1 votes

# Answer
## Perl 5, 49 bytes

```
sleep say"chello world"^""x$_.$"x!/7/ for 2..12

```

Try it online! \- only really works in a terminal, but you can easily copy/paste from here.

## Explanation

This script uses the stringwise `XOR` operation to capitalise the needed letters in each iteration. First we build the string `'hello world'` (which includes `\x1bc` as an ANSI escape sequence to clear the screen), then we `XOR` (`^`) against a string of repeating `NUL` bytes (repeating as needed, 2 on the first iteration and finishing with 12), followed by a space (`$"`) on all but the 7th iteration (which would remove the space in the middle - well, set it to `NUL`).

Please note this script contains unprintables, here's a reversible hex dump:

```
00000000: 736c 6565 7020 7361 7922 1b63 6865 6c6c  sleep say".chell
00000010: 6f20 776f 726c 6422 5e22 0022 7824 5f2e  o world"^"."x$_.
00000020: 2422 7821 2f37 2f20 666f 7220 322e 2e31  $"x!/7/ for 2..1
00000030: 32                                       2

```
> 1 votes

# Answer
# x86 opcode(.COM), 48 bytes

```
  org 100h
  mov ax, 0x0900
  mov bx, -34
  out 0x70,al
  mov dx, stri
  int 0x21
  push 0xa802
  pop ds
r:in  al,0x71
  cmp al,cl
  jz  r
  xchg ax,cx
  xor [bx],dword 0x200020
  add bx, 2
  jnz r
  stri db 'hello world$'

```
> 1 votes

# Answer
# Small Basic, 166 bytes

Takes no input and outputs to the `TextWindow`.

```
For i=1To 11
l=0
t="hello world
p()
l=i-1
t=Text.GetSubText("HELLO WORLD",i,1)
p()
Program.Delay(1000)
EndFor
Sub p
TextWindow.CursorLeft=l
TextWindow.Write(t)
EndSub

```

Try it at SmallBasic.com! *Requires Silverlight/IE*
> 1 votes

# Answer
# Forth (gforth), 103 bytes

```
: f s" hello world"11 0 do page over dup i type i + dup c@ toupper emit 1+ over i - type 1000 ms loop ;

```

Try it online!

Doesn't work properly in TIO, but if you copy and paste into a gforth interpreter/terminal you get a proper animation.

I overwrote `page` and `1000` in the tio header so the output was readable and didn't take 10+ seconds to render, but the value in the "code" box is correct

### Explanation

Loops through all characters in "hello world". For each one:

* Clear screen and set cursor to top left of terminal/window
* Output all characters before the current one
* Output the current character uppercase (or as-is for space)
* Output all characters after the current one
* Wait 1 sec (1000 milliseconds)

### Code Explanation

```
: f                 \ start a new word definition
  s" hello world"   \ create a string containing "hello world"
  11 0              \ set up loop parameters
  do                \ loop from 0 to 10 inclusive
    page            \ clear the screen/terminal and set cursor to top left
    over            \ get the string's starting address
    dup i type      \ output the first i characters of the string
    i + dup c@      \ get the value at the address of the current character
    toupper emit    \ convert to uppercase and output
    1+ over i -     \ add 1 to address, subtract current index from string length
    type            \ output end of string
    1000 ms         \ wait 1 seconds
  loop              \ end loop
;                   \ end word definition

```
> 1 votes

# Answer
# Stax, 22 bytes

```
▒4↓σ┘«☼⌡♥Åα≡♂%Ç$K¥╞▲▓►

```

Run and debug it

delaying takes a lotta bytes.
> 1 votes

# Answer
**PowerShell, 76 bytes**

```
$b= # The solution is the next line
{$a=[char[]]$_;1..$a.length|%{$a[--$_]-=32;cls;-join$a;$a[$_]-=-32;sleep 1}}
'hello world'|% $b

```
> 0 votes

# Answer
# ES2015, 126 bytes

Based on this answer.

```
c=console;d=0;t=_=>setTimeout(_=>{a=[...`hello world`];a[d]?c.clear(a[d]=a[d++].toUpperCase())|t(c.log(a.join``)):a},1e3);t()
```
> 0 votes

# Answer
# Mathematica, 104 bytes

```
Monitor[Do[s=y=Characters@"hello world";s=s~Delete~i;Pause@1,{i,11}],""<>Insert[s,Capitalize[y][[i]],i]]

```
> 0 votes

# Answer
# C# (Visual C# Compiler), 217 bytes

```
using u=System.Console;class P{static string a="hello world";static void Main(){for(int i=0;i<11;i++){u.Clear();u.WriteLine(a.Substring(0,i)+char.ToUpper(a[i])+a.Substring(i+1));System.Threading.Thread.Sleep(1000);}}}

```

Try it online!
> 0 votes

# Answer
# Haskell, 161 bytes

```
import Data.Char;import System.IO;main=mapM(\x->do putStr$('\b'<$z)++[(toUpper v:(v<$z))!!abs(k-x)|(v,k)<-zip"hello world"z];hWaitForInput stdin 1000)z;z=[0..10]

```

Unfortunately it doesn't quite work in TIO.
> 0 votes

---
Tags: code-golf, string, hello-world, animation
---


title: Is it a valid line in "Girls & Boys"?

text:
# Question
Title: Is it a valid line in "Girls & Boys"?
## Intro

Blur's song *Girls & Boys* featured the lines

```
girls who are boys who like boys to be girls
who do boys like they're girls, who do girls like they're boys

```

in the chorus. These lines have a pretty uniform structure: you have a subject, which is either `girls` or `boys`, a relative clause, either `who are`, `who like`, or `who do`, an object, again either `girls` or `boys`, and an optional modifier, which is similar to the relative clause, except it can also be `like they're` or `to be`. In EBNF this might be written as:

```
subject ::= "boys" | "girls"
relative_clause ::= "who are" | "who like" | "who do"
modifier ::= relative_clause | "like theyre" | "to be"
tail ::= relative_clause subject (modifier sentence)?
sentence ::= subject tail

```

## The challenge

Your task is to, given a string, see if it is valid in this format. you can assume the string will be all lowercase, and will contain only letters and spaces (this means that `theyre` will have no apostrophe). It should output a boolean value or `0`/`1`. input and output can be done with any of the standard I/O methods. the input string may be empty. all words will be separated by a single space, but they will not all be valid words. for example, the input will never be `girls who likeboys` but it might be `girls who like bananas`

## Example I/O

```
girls who are boys who like boys to be girls who do boys like theyre girls who do girls like theyre boys -> true

boys who like boys -> true
true

girls to be boys -> false
`to be` is only valid in the modifier position, not as the leading relative clause.

girls who like boys to be girls to be boys -> false
The second `to be` is used in the relative clause position here, since after the first `to be` a new sentence begins, and sentences can't use modifiers in the relative clause position.

boys -> false

boys who are -> false

who are boys -> false

boys boys -> false

<empty input> -> false

```

## Scoring

This is , so the shortest answer in characters wins.

# Answer
> 1 votes
# Retina 0.8.2, 99 bytes

```
^(boy|girl)s( who (are|like|do) (boy|girl)s( (who (are|like|do)|like theyre|to be) (boy|girl)s)?)+$

```

Try it online! Link includes test cases. Simply the grammar turned into a regex and optimised slightly.

# Answer
> 1 votes
# Perl 5 `(-p)`, ~~82~~, 80 bytes

From @Neil's Retina answer, but using recursive regex.

-2 thanks to @DomHastings.

```
$_=/^(boys|girls)( (who (are|like|do)) (?1)( ((?3)|like theyre|to be) (?1))?)+$/

```

Try it online!

# Answer
> 0 votes
# PEG.js, 92 bytes

```
S=s r" "s(m" "S)?
s="boys"/"girls"
r=" who "("are"/"like"/"do")
m=r/" like theyare"/" to be"

```

https://pegjs.org/online

---
Tags: code-golf, string, decision-problem, parsing, natural-language
---


title: Flood-fill a 2D grid

text:
# Question
Title: Flood-fill a 2D grid
# Challenge description

Let's call a two-dimentional, rectangular array (meaning its every subarray has the same length), a **grid**. Every unit of a grid is either an **empty space** or a **border**. In a grid of characters, empty space is represented by a single whitespace; any other character is treated as a border. Sample grids (`+`'s, `|`'s and `-`'s added for readability - *they are not part of the grid*):

```
+----+
|    |
|    |
|    |
|    |
|    |
+----+  an empty 4x5 grid

+------+
|      |
|  #   |
|  #   |
+------+  a 6x3 grid with 2 borders

+----------+
|          |
|          |
|  #####   |
|  #   #   |
| ##   # <------ enclosed area
| #    #   |
| ######   |
|          |
+----------+  a 10x8 grid with an enclosed area

```

Given a 2D grid and a pair of coordinates, fill the enclosed area surrounding the point represented by the coordinates.

# Sample inputs / outputs

**1)**

```
0 0
+----------+      +----------+
|          |      |XXXXXXXXXX|
|          |  ->  |XXXXXXXXXX|
|          |      |XXXXXXXXXX|
+----------+      +----------+

```

**2)**

```
6 5
+-----------------+      +-----------------+
|                 |      |                 |
|                 |      |                 |
|    ########     |      |    ########     |
|    #       #    |      |    #XXXXXXX#    |
|    #    ####    |      |    #XXXX####    |
|    #    #       |      |    #XXXX#       |
|    #    #       |  ->  |    #XXXX#       |
|    #    #       |      |    #XXXX#       |
|     ####        |      |     ####        |
|                 |      |                 |
|                 |      |                 |
+-----------------+      +-----------------+

```

**3)**

```
4 6
+-----------------+      +-----------------+
|                 |      |XXXXXXXXXXXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|   #    #        |  ->  |XXX#    #XXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|                 |      |XXXXXXXXXXXXXXXXX|
+-----------------+      +-----------------+

```

**4)**

```
4 5
+-----------------+      +-----------------+      +-----------------+
|                 |      |                 |      |                 |
|                 |      |                 |      |                 |
|    ####         |      |    ####         |      |     XXXX        |
|    ####         |  ->  |    ####         |  or  |     XXXX        |
|    ####         |      |    ####         |      |     XXXX        |
|                 |      |                 |      |                 |
+-----------------+      +-----------------+      +-----------------+

```

**5)**

```
2 6
+----------------+      +----------------+
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |  ->  |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|BBBBBBBBBBBBBBBB|      |BBBBBBBBBBBBBBBB|
|                |      |                |
|                |      |                |
+----------------+      +----------------+

```

# Notes

* An empty grid is considered enclosed, i.e. borders are implicitly situated along the edges of the grid as well (see examples 1. and 5.),
* A corner of an enclosed area doesn't need to be L-shaped. The following two areas are therefore equivalent:

```
####         ##
#  #        #  #
#  #   ==   #  #
#  #        #  #
####         ##

```
* If a unit under the coordinates happens to be a border you can either leave the grid unchanged (as in example 4.) or treat it as an empty space,
* You can choose any character for filler / empty space as long as you include this information in the submission,
* If using a type other than `char` suits your purposes better, you can use `ints` (`0` for empty space, `1` for border) or `booleans` (`true` and `false` respectively) or any other type - just make sure to include this information in your submission,
* Coordinates used in the examples above are 0-indexed `(row, column)` coordinates, as it's more convenient for two-dimensional array. If you want to use `(column, row)` (cartesian) system and/or non-0-indexed coordinates, specify it in your submission.
* If you don't know where to start, check out Wikipedia article on flood fill
* Remember that this is a challenge, so make your code as short as possible!

# Answer
# MATLAB, ~~30~~ 7 bytes

As we can use logical inputs instead of strings, we can use the bare function, as it is:

```
@imfill

```

This is an anonymous function. For the usage, we have to assume a name, e.g. `f=@``imfill`. Then we can just evaluate it as `f(input,point)`, where `input` is a logical matrix, e.g. `[0,0;0,1]`, and `point` is a 2d-vector with 1-based coordinates, e.g. `[1,2]`.

Old version working on strings:

```
@(a,p)[imfill(a>32,p)*3+32,'']

```

This anonymous function accepts the input as well as a vector with the coordinates (1-based index). The function `imfill` does exactly what we need, but operates only on binary images. That is why we convert the input matrix to a logical array (where `#` are the boundaries, and  (spaces) are the void), performs the filling and is then converted back. (again `#` is filled, space is not filled).

Thanks @LuisMendo for -~~1~~ byte.
> 4 votes

# Answer
# C, 162 bytes

```
w,l;char*d;f(z){z<0||z>l||d[z]^32||++d[z]&&f(z+1)+f(z-1)+f(z+w)+f(z-w);}main(c,v)char**v;{l=strlen(d=v[3]),w=strchr(d,10)-d+1,f(atoi(v[2])*w+atoi(v[1]));puts(d);}

```

Takes input from arguments (`./floodfill X Y grid`). Grid must contain `\n` or `\r\n` between each line, final newline is optional. Simplest way I've found to invoke from shell:

```
./floodfill 1 0 "$(printf "   \n###\n   \n")"
# or
./floodfill 1 0 "$(cat gridfile)"

```

Outputs to stdout, using `!` for the fill character. If the start position coincides with a `#`, makes no change.

### Breakdown:

```
                                    // GCC is happy enough without any imports
w,l;                                // Globals (line width, total length)
char*d;                             // Global grid pointer
f(z){                               // "Fill" function - z=current cell
    z<0||z>l||                      // Check if out-of-bounds...
    d[z]^32||                       // ...or not empty
        ++d[z]&&                    // Fill cell...
        f(z+1)+f(z-1)+f(z+w)+f(z-w);// ...and continue in "+" pattern
}
main(c,v)char**v;{                  // K&R style function to save 2 bytes
    l=strlen(d=v[3]),               // Store grid & length
    w=strchr(d,10)-d+1,             // Store width of grid (including newlines)
    f(atoi(v[2])*w+atoi(v[1]));     // Parse X & Y arguments and invoke fill

    puts(d);}                       // Print the result

```

Note that this relies on modifying the input argument string, which is forbidden, so this may not work on all platforms (implicit declarations also make this non-standard).
> 4 votes

# Answer
# C - ~~263~~ ~~247~~ ~~240~~ 238 bytes

*This is ~~first~~ ~~second~~ third version, I believe code can be shrinked too.*

```
m[99][99],x,y,a,b,c,n;f(v,w){if(m[v][w]==32){m[v][w]=88;f(v,w+1);f(v+1,w);f(v,w-1);f(v-1,w);}}main(){scanf("%d %d\n",&a,&b);for(;~(c=getchar());m[x++][y]=c,n=x>n?x:n)c==10&&++y&&(x=0);f(b+2,a+1);for(a=-1;++a<y*n+n;)putchar(m[a%n][a/n]);}

```

And readable version:

```
m[99][99], x, y, a, b, c, n;

/*
    a, b - flood fill start coordinates
    v, w - recursive function start coordinates
    x, y - iterators
    c - character read
    m - map
    n - maximum map width found

*/

//Recursive flood function
f( v, w )
{
    if ( m[v][w] == 32 ) //If field is empty (is ' '?)
    {
        m[v][w] = 88; //Put 'X' there
        f(v,w+1);f(v+1,w); //Call itself on neighbour fields
        f(v,w-1);f(v-1,w);
    }
}

main( )
{
    //Read coordinates
    scanf( "%d %d\n", &a, &b );

    //Read map (put character in map, track maximum width)
    for ( ; ~( c = getchar( ) ); m[x++][y] = c, n = x > n ? x : n )
        c == 10 && ++y && ( x = 0 );

    //Flood map
    f( b + 2, a + 1 );

    //Draw
    for ( a = -1; ++a < y * n + n; )
            putchar( m[a % n][a / n] );

}

```

Compile and run:
`gcc -o flood floodgolf.c && cat 1.txt | ./flood`

Resources:

*Note: I'm working on `int` values. Every  (32) is treated as empty space. Any other value is treated as border. Coordinates are in format `(row, column)`*
> 1 votes

# Answer
## Python 2, 158 bytes

Try it online. Simple recursive solution

```
a,X,Y=input()
M=len(a)
N=len(a[0])
def R(x,y):
 if~0<x<M and~0<y<N and a[x][y]:a[x][y]=0;R(x-1,y);R(x+1,y);R(x,y-1);R(x,y+1)
R(X,Y)
print'\n'.join(map(str,a))

```

0-indexed in row-column order

1 - empty space, 0 - filled space

Takes input as array of arrays of 1 and 0, and two numbers
> 1 votes

# Answer
# Perl 5, 129 + 1 (-a) = 130 bytes

```
sub f{my($r,$c)=@_;$a[$r][$c]eq$"&&($a[$r][$c]=X)&&map{f($r+$_,$c);f($r,$c+$_)}-1,1}@a=map[/./g],<>;f$F[0]+1,$F[1]+1;say@$_ for@a

```

Try it online!

**How?**

```
sub f{   # recursive subroutine
  my($r,$c)=@_; # taking row and column as inputs
  $a[$r][$c]eq$"&&  # using Boolean short circuit as an 'if' statement to
                    # check if the current position in the global array is blank
  ($a[$r][$c]=X)&&  # then setting it to 'X'
  map{f($r+$_,$c);f($r,$c+$_)}-1,1 # and checking the four surrounding spaces
}
# -a command line option implicitly splits the first line into the @F array
@a=map[/./g],<>;    # put the input in a 2-D array
f$F[0]+1,$F[1]+1;   # start the fill at the given position, correcting for
                    # Perl's 0 based arrays
say@$_ for@a        # output the resulting pattern

```
> 1 votes

# Answer
# 05AB1E, 53 bytes

```
[©g_#®ć©d®IgIнg‚‹«PisD®нèD®θèi2®θǝ®нǝs1ÝÂ‚D(«ε®+}ìë\s

```

Input-coordinate as a wrapped pair of integers \\$\[\[x,y\]\]\\$, and input-grid as a matrix of 1s and 0s for empty spaces and borders respectively. Flood-fills with 2s.

Try it online or verify all test cases. (The `]J»` in the footer of the single TIO is used to pretty-print the output-matrix. Feel free to remove it to see the actual output.)

**Explanation:**

Despite being a codegolf language, 05AB1E's matrix builtins aren't too useful here. And 05AB1E's modular indexing is only a disadvantage for a challenge like this, where you want to stay within the dimension of the grid.

```
[                  # Start an infinite loop:
 ©                 #  Store the list of coordinates in variable `®` (without
                   #  popping)
                   #  (which is the first implicit input in the first iteration)
  g_               #  If it's empty:
    #              #   Stop the infinite loop
  ©ć               #  Extract head of `®`; pop and remainder-list and first
                   #  coordinate separated to the stack
    ©              #  Store this coordinate as new variable `®` (without popping)
     d             #  Check [x>=0,y>=0]
       Ig          #  Push the amount of rows of the input-matrix
         Iнg       #  Push the amount of columns of the input-matrix
            ‚      #  Pair them together
      ®      ‹     #  Check [x<rowCount,y<columnCount]
              «    #  Merge the two lists together
               Pi  #  Pop, and if all were truthy (so [x,y] is within bounds):
 s                 #   Swap so the matrix is at the top
  D                #   Duplicate this matrix
   ®нè             #   Pop and get the x'th (of coordinate `®`) row of the matrix
      D            #   Duplicate this row
       ®θè         #   Pop and get the y'th (of coordinate `®`) cell of this row
          i        #   If this value is 1:
           2®θǝ    #    Insert a 2 at this y'th cell of the row
               ®нǝ #    Insert this modified x'th row into the matrix
 s                 #    Swap so the list of coordinates is at the top again
  1Ý               #    Push [0,1]
    Â‚             #    Bifurcate (Duplicate & Reverse copy) and pair:
                   #    [[0,1],[1,0]]
      D(«          #    Duplicate, negate, merge: [[0,1],[1,0],[0,-1],[-1,0]]
         ε®+}      #    Add coordinate `®` to each pair:
                   #    [[x,y+1],[x+1,y],[x,y-1],[x-1,y]]
             ì     #    Prepend-merge it at the front of the coordinates-list
          ë        #   Else: the value was 0 or 2 instead:
           \       #    Discard the duplicated row
            s      #    And swap so the coordinates list is at the top again
]                  # Close the open if-statements and infinite loop
 \                 # Discard the empty coordinates list
                   # (after which the matrix is output implicitly as result)

```
> 1 votes

# Answer
# Java, 112 bytes

```
int f(int[][]m,int x,int y){try{if(m[x][y]==0)f(m,x+f(m,x,y+f(m,x-f(m,x,y+--m[x][y]),y)),y);}finally{return 1;}}

```

Input as a matrix of 0s and 1s for empty spaces and borders respectively. Modifies the input-matrix directly, and flood-fills with -1s.

Uses the same flood-fill recursive method I've used in this answer, this answer, and this answer of mine.

Try it online.

**Explanation:**

```
// Recursive method with integer matrix & x,y parameters and integer return-type
int f(int[][]m,int x,int y){
  try{if(m[x][y]==0)   //  If the current cell-value is 0:
            --m[x][y]  //   Decrement the current cell-value to -1
           f(m,x,y+...)//   Recursive call west
          f(m,x-...,y) //   Recursive call north
         f(m,x,y+...)  //   Recursive call east
        f(m,x+...,y);  //   Recursive call south
  }finally{            //  Catch and swallow any ArrayIndexOutOfBoundsExceptions
                       //  (shorter than manual if-checks)
           return 1;}  //  Always result in 1, so we use it to our advantage to
                       //  save bytes here by nesting, instead of having four
                       //  loose calls to each direction)

```
> 1 votes

---
Tags: code-golf, array, grid
---


title: Detriplicate a string

text:
# Question
Title: Detriplicate a string
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first *two* occurrences are kept.

Here is an example where the characters that should be deleted are labelled with `^`:

```
aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd

```

Your task is to implement exactly this operation.

## Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

Every pair of lines is one test case, input followed by output.

```

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd

```

### Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 3 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 86503; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 24 votes
# Jelly, 6 bytes

```
Qx2œ&@

```

Try it online! or verify all test cases.

### How it works

```
Qx2œ&@  Main link. Argument: s (string)

Q       Unique; deduplicate s.
 x2     Repeat each character.
   œ&@  Take the multiset intersection of s and the previous result.

```

# Answer
> 15 votes
# JavaScript (ES6), 42 ~~48~~

**Edit** A whopping 6 bytes saved thx @Neil

```
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

```

Explanation: I use the properties 'a'...'z' of object `k` to store info for each character (object k is a regexp in this case just to save bytes). These properties are initially `undefined`. In javascript adding a number to `undefined` gives `NaN` (quite sensible), but adding a string 'X' gives `"undefinedX"` \- a string of length 10 (silly). Adding more characters you get longer strings. If the obtained string for a given character is longer than 11, that character is not copied to output.

**Test**

```
F=
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

test=`

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd`.split`\n`
for(i=0;i<test.length;)
  a=test[i++],b=test[i++],r=F(a),
  console.log(r==b?'OK':'KO',a,'->',r,b)
```

# Answer
> 14 votes
## Python 2, 48 bytes

```
lambda s:reduce(lambda r,c:r+c*(r.count(c)<2),s)

```

`c[r.count(c)/2:]` is a same-length alternative to `c*(r.count(c)<2)` .

---

**49 bytes:**

```
r=''
for c in input():r+=c*(r.count(c)<2)
print r

```

# Answer
> 12 votes
# Retina, 17 bytes

```
(.)(?<=\1.*\1.+)

```

Try it online!

Simple regex replace - match a character if it already appeared twice, and remove it.

# Answer
> 6 votes
# Brachylog, 25 bytes

```
.v|s.g:.z:1a
:2fl<3
he~t?

```

Try it online! or verify all test cases.

### Explanation

This works because `s - Subset` will unify with bigger subsets first, thus e.g. for `"aaa"` it will try `"aa"` before `"a"`.

* Main predicate:

```
  .v         input = Output = ""
|          Or
  s.         Output is an ordered subset of the input
  g:.z       Zip each character of the output with the output itself
  :1a        Apply predicate 1 on each element of the zip

```
* Predicate 1: Check that all characters only appear at most twice. Input = `[String:Char]`

```
:2f        Find all valid outputs of predicate 2 (i.e. one output per occurence
               of the char)
l<3        There are less than 3 occurences

```
* Predicate 2: Get an occurence of a character. Input = `[String:Char]`

```
he         Take a character of the string in the input
  ~t?      That character is the char of the input

```

# Answer
> 6 votes
## \>\<\>, 22 bytes

```
i:0(?;::9g:}2(?o{1+$9p

```

Try it online! Uses the codebox to keep track of counts so far.

```
i                       Read a char c of input
 :0(?;                  Halt if EOF
      :                 Make a copy - stack has [c c] at the top
       :9g              Get count stored at (c, 9)
          :}            Copy the count and move to bottom of stack
            2(?o        If the count is less than 2, output c
                {1+     Move the count back to the top of the stack and increment
                   $9p  Update cell at (c, 9)
                        [Instruction pointer moves to start as ><> is toroidal]

```

# Answer
> 6 votes
## J, ~~20~~ 15 bytes

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

```

This defines a monadic function that takes and returns a string. Try it here. Usage:

```
   f =: #~(3>[+/@:={:)\
   f 'abaacbb'
abacb

```

## Explanation

I switched to the same algorithm that some other solutions use, since it turned out to be shorter...

```
#~(3>[+/@:={:)\  Input is y.
  (          )\  For each prefix of y:
          =        compute the equality vector
     [     {:      of the prefix and its last element, and
      +/@:         take its sum. Now we have a vector r such that y[i] has its
                   r[i]'th occurrence at position i.
   3>              Mark those coordinates where r[i] < 3.
#~               Remove the non-marked characters from y.

```

# Answer
> 6 votes
## Haskell, ~~40~~ 39 bytes

```
foldl(\s c->s++[c|filter(==c)s<=[c]])""

```

Usage example: `foldl(\s c->s++[c|filter(==c)s<=[c]])"" "aaabcbccdbabdcd"` -\> `"aabcbcdd"`.

Keep the next char `c` if the string of all `c`s so far are lexicographical less or equal the singleton string `[c]`.

Edit: @xnor saved a byte by switching from list comprehension to `filter`. Thanks!

# Answer
> 5 votes
## Perl, 22 bytes

**21 bytes code + 1 for `-p`.**

```
s/./$&x(2>${$&}++)/ge

```

### Usage

```
perl -pe 's/./$&x(2>${$&}++)/ge' <<< 'aaabcbccdbabdcd'
aabcbcdd

```

# Answer
> 5 votes
# C, 57 bytes

Call `f()` with the string to detriplicate. The function modifies its parameter. Requires C99 because of the `for`-loop declaration.

```
f(char*p){for(char*s=p,m[256]={0};*s=*p;s+=++m[*p++]<3);}

```

# Answer
> 5 votes
# JavaScript (ES6), 35 bytes

```
s=>s.filter(c=>(s[c]=(s[c]|0)+1)<3)

```

Takes an array of characters as input and returns the detriplicated array.

# Answer
> 4 votes
# MATL, 8 bytes

```
t&=Rs3<)

```

**Try it online!**

### Explanation

```
t      % Input string implicitly. Push another copy
&=     % Matrix of all pairwise equality comparisons of string elements
R      % Keep only upper triangular part, making the rest of the entries zero
s      % Sum of each column. This gives a vector with number of occurrences
       % of the current character up to the current position
3<     % True for entries that are less than 3
)      % Use as logical index into initial copy of the input. Display implicitly

```

### Example

Assuming input `'aaababbc'`, the stack contains the following after the indicated statements:

* `t`

```
'aaababbc'
'aaababbc'

```
* `t&=`

```
'aaababbc'
[ 1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 0 0 0 1 ]

```
* `t&=R`

```
'aaababbc'
[ 1 1 1 0 1 0 0 0;
  0 1 1 0 1 0 0 0;
  0 0 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 1 0 0 0;
  0 0 0 0 0 1 1 0;
  0 0 0 0 0 0 1 0;
  0 0 0 0 0 0 0 1 ]

```
* `t&=Rs`

```
'aaababbc'
[ 1 2 3 1 4 2 3 1 ]

```
* `t&=Rs3<`

```
'aaababbc'
[ true true false true false true false true ]

```
* `t&=Rs3<)`

```
'aabbc'

```

# Answer
> 4 votes
## PowerShell v2+, 31 bytes

```
$args-replace'(.)(?<=\1.*\1.+)'

```

Uses the same regex as in Kobi's Retina answer, just encapsulated in the PowerShell `-replace` operator. Works because both are using .NET-flavor regex in the background.

### Alternatively, without regex, 56 bytes

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

```

Creates a helper array `$b` pre-populated with `0`s. Casts the input string `$args[0]` as a `char`-array, pipes it through a loop `|%{...}`. Each iteration outputs the current character `$_` as a string `"$_"` multiplied by a Boolean that is only `$TRUE` (implicitly cast to `1` here) if the appropriate point in the helper array is less than `2` (i.e., we haven't seen this char twice already). The resultant collection of strings is encapsulated in parens and `-join`ed together to form a single output string. That's left on the pipeline and output is implicit.

# Answer
> 4 votes
# Mathematica, 39 bytes

```
Fold[If[Count@##<2,Append@##,#]&,{},#]&

```

Anonymous function. Takes a character list as input, and returns the detriplicated list as output. Uses the method of folding over the list and rejecting triplicate elements, it's not too complicated.

# Answer
> 4 votes
## 05AB1E, 12 bytes

```
vyˆ¯y¢O3‹iy?

```

**Explanation**

```
v            # for each char in input
 yˆ          # push to global array
   ¯y¢O3‹i   # if nr of occurrences are less than 3
          y? # print it

```

Try it online

# Answer
> 4 votes
## Retina, 14 bytes

```
D`(.)(?<=\1.*)

```

Verify all test cases. (The `%` enables per-line mode)

Uses the new "Deduplicate" stage to save a couple bytes over Kobi's approach. Deduplicate gathers a list of all matches to the regex and replaces all but the first with the empty string. The regex matches a character that already appears once in the string, meaning that the first two will be kept.

# Answer
> 4 votes
## K, 18 Bytes

```
  g:{x{?x@<x}@,/2#'=x}
  g "abc"
"abc"
  g "aaabcbccdbabdcd"
"aabcbcdd"

  /k4 request test vectors from internet
  R:"GET /raw/ftHe0bpE HTTP/1.0\r\nHost: pastebin.com\r\n\r\n"
  t:+0N 2#t@1_&|\(0=#:)'t:1_"\r\n"\:`:http://pastebin.com:80 R

  /k4 no internet? use a file called "t.txt" in current directory
  t:+0N 2#0:`:t.txt

  /k6?
  t:+0N 2#0:"t.txt"

  /visually inspect test cases
  g't[0]
(();"xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd")

  /do all tests pass?
  |/ t[1] {$[0=#x;0=#y;x~y]}' g't[0]
1b

```

K4 is available for free download; K6 is in development. If you've downloaded KDB, you can get into K with backslash.

It may be easiest to see this broken apart, but first some syntax: `g:x` sets `g` to `x`. `{x+1}` is a function which takes an argument *x*. In K the first argument to a function is `x` (the second is `y` and the third is `z`. Don't need a fourth).

Now:

```
x:"aaabcbccdbabdcd"

```

`=x` means *group x*, which produces:

```
"abcd"!(0 1 2 10;3 5 9 11;4 6 7 13;8 12 14)

```

`2#'` means *two taken(from) each* which produces

```
"abcd"!(0 1;3 5;4 6;8 12)

```

As you can see, these are the offsets of the first two matches of each character. The *2* could be generalised.

`,/` means *join each* and is often called raze. It's going to get us just the values of our dictionary. Thus, `,/"abcd"!(0 1;3 5;4 6;8 12)` produces:

```
0 1 3 5 4 6 8 12

```

which we need to sort. `{x@<x}@` is an idiom K programmers often see (Q calls it asc), which says *x at grade-up x*. Breaking it apart:

```
  <0 1 3 5 4 6 8 12
0 1 2 4 3 5 6 7

```

returned the indices of the sorted array, which we want taken from the original array. `x@y` means *x at y* so this indexes the array with the indices of the sort (if that makes any sense).

```
  {x@<x}@0 1 3 5 4 6 8 12
0 1 3 4 5 6 8 12

```

which we simply now index into our original array. We *could* say `x@` here, but K supports a really powerful concept which we can take advantage of here: function application is indexing. That means that `a[0]` could be looking up the zeroth slot of `a` or it could be applying the `0` to the function called `a`. The reason we needed the `@` previously in `{x@<x}` is because `x<y` means *xs less than ys*: Operators in K have a dyadic form (two-argument) and a monadic form (one-argument) that comes from APL.  doesn't have this "ambivalence".

# Answer
> 3 votes
## Pyke, 16 bytes

```
F~kR/2<Ii?+k(K~k

```

Try it here!

# Answer
> 2 votes
# Python 2, 51 bytes

```
f=lambda s:s and f(s[:-1])+s[-1]*(s.count(s[-1])<3)

```

Test it on Ideone.

# Answer
> 2 votes
# Perl 6, 27 bytes

```
{.comb.grep({++%.{$_} <3})}

```

Explanation:

```
{.comb.grep({++%.{$_} <3})}
{                         } # a function
 .comb                      # get all the characters in the argument
      .grep({           })  # filter
               %.           # an anonymous hash (shared between calls to grep)
             ++  {$_}       # increment the value at the current key (current letter).
                            # if the key doesn't exist, it defaults to 0 (then gets incremented)
                      <3    # return True if it wasn't seen 3 times

```

(Note: Perl 6 isn't as "golf-oriented" as its sister Perl 5 ... So yes, that space before the `<` is necessary. The `%.{}` is an anonymous hash).

# Answer
> 2 votes
## Java 8 lambda, 90 characters

```
i->{int[]o=new int[128];String r="";for(char c:i.toCharArray())if(++o[c]<3)r+=c;return r;}

```

Ungolfed version:

```
public class Q86503 {

    static String detriplicate(String input) {
        int[] occurences = new int[128];
        String result = "";
        for (char c : input.toCharArray()) {
            if (++occurences[c] < 3) {
                result += c;
            }
        }
        return result;
    }
}

```

Creates an array for all ascii characters. If a character occurs the corresponding counter will be increased. If it is over 2 the character won't be appended to the result string. Very easy, very short ;)

# Answer
> 2 votes
# SmileBASIC, ~~77~~ ~~72~~ ~~69~~ 68 bytes

```
DIM R[#Y]READ S$WHILE""<S$Q=ASC(S$)INC R[Q]?SHIFT(S$)*(R[Q]<3);
WEND

```

Explained:

```
DIM R[128] 'array to store letter frequencies
READ S$ 'get input string
WHILE""<S$ 'much shorter than LEN(S$)
 Q=ASC(S$) 'get ascii value of first character in S$
 INC R[Q]
 ?SHIFT(S$)*(R[Q]<3); 'remove the first character of S$, and print it if there are less than 3 occurrences.
WEND

```

# Answer
> 1 votes
## Common Lisp, 127

```
(lambda(s)(map()(lambda(x)(flet((p(b)(1+(position x s :start b))))(setf s(remove x s :start(p(p 0))))))(remove-duplicates s))s)

```

### Pretty-printed

```
(lambda (s)
  (map nil
       (lambda (x)
         (flet ((p (b)
                  (1+ (position x s :start b))))
           (setf s (remove x s :start (p (p 0))))))
       (remove-duplicates s))
  s)

```

# Answer
> 1 votes
# Ruby, ~~79~~ ~~62~~ 57 bytes

This is pretty unwieldy, but I'm not sure I can golf this much better at the moment. Any golfing suggestions are welcome. Try it online!

**Edit:** -17 bytes thanks to Value Ink by suggesting a golfier way to remove triplicate characters. -5 bytes from removing the `.uniq` method.

```
->s{s.chars.map{|a|s[s.rindex a]=""while s.count(a)>2};s}

```

**Ungolfed:**

```
def g(s)
 s.chars.each do |a|
  while s.count(a) > 2
   i = s.rindex(a)
   s[i] = ""
  end
 end
 return s
end

```

# Answer
> 1 votes
## , 27 Bytes

```
    f:{x{x@<x}@,/{?2#&x}'x~'/:?x}
    testList:("xxxxx";"abcabc";"abcdabcaba";"abacbadcba";"aaabcbccdbabdcd")
    f'testList
("xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd")

```

# Answer
> 1 votes
## , 52 Bytes

```
q)f2:{x asc raze{distinct 2#where x}each x~'/:distinct x}
q)f2 each testList
"xx"
"abcabc"
"abcdabc"
"abacbdc"
"aabcbcdd"
q)

```

# Answer
> 1 votes
# JavaScript, 30 bytes

```
v=>v.filter(x=>!(v[x]+=x)[11])

```

Using the method that @edc65 came up with for counting but with an array filter. First time character appears, the object value gets "undefined" plus the character (i.e. "undefinedx"). The next time the object value becomes "undefinedxx".

After that, v\[x\]\[11\] returns true and when combined with the not operator, false, meaning characters that have already appeared twice will be filtered.

# Answer
> 1 votes
# Kotlin, 50 bytes

```
{it.filterIndexed{i,c->it.take(i).count{it==c}<2}}

```

Try it online!

# Answer
> 1 votes
# PHP, 42 bytes

Loop through the string, count each character in an array, only echo if the letter hasn't reached a count of 3 yet.

```
while($e=$argn[$x++])if($s[$e]++<2)echo$e;

```

Try it online!

# Answer
> 1 votes
# C (gcc), 85 bytes

```
int f(char*i){int v[255]={};int x,y;x=y=0;do++v[i[x]]<3?i[y++]=i[x]:0;while(i[x++]);}

```

Try it online!

de-golfed version:

```
int f(char* i)
{
    int v[255]={};
    int x,y;
    x=y=0;
    do
    {
        ++v[i[x]]<3?i[y++]=i[x]:0;
    }while(i[x++]);
}

```

Takes input as an array of characters and outputs by updating it in-place.

# Answer
> 1 votes
# Pure Zsh, 35 bytes

```
eval ';1=${(I:3:)1//'{a..z}\}
<<<$1
```

Attempt This Online!

Explanation:

* `eval` `{a..z}`: for each letter:
    + `$1`: in the input:
    + `{//}`: replace all matches of that letter
    + `(I:3:)`: but only replace starting with the third match
    + `;1=`: and update the input to that new string
* `<<<$1`: print the variable `$1`

# Answer
> 0 votes
## Javascript (using external library) (80 bytes)

This was a good one! Didn't win but it was fun

```
n=>{a={};return _.From(n).Where(x=>{b=a[x]?a[x]++:a[x]=1;return b<2}).Write("")}

```

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: Method accepts a string, library parses it as a char array, and the Where clause is a complex filtering predicate that checks the 'a' hashmap for presence of the current char. If exists, increment counter, else set to 1. If \< 2, the predicate (and current char) passes, else fail

# Answer
> 0 votes
## Clojure, 72 bytes

```
#(apply str(reduce(fn[r c](if(<(count(filter #{c}r))2)(conj r c)r))[]%))

```

So many bytes...

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

```
var a:array['a'..'z']of word;c:char;begin repeat read(c);inc(a[c]);if a[c]<3then write(c)until eof end.

```

Try it online!

### Explanation:

```
var a:array['a'..'z']of word; //used for counting occurences of characters in the input
                              //array indices are accessed by chars
    c:char;
begin
  repeat
    read(c);                  //read a character from input
    inc(a[c]);                //increment the count of that character (its number in array)
    if a[c]<3 then write(c)   //if this is character's 1st or 2nd occurence, output it
  until eof                   //go back to reading if input is not read completely
end.

```

# Answer
> 0 votes
# sed (with -r), 25 bytes

```
:x;s/((.).*\2.*)\2/\1/;tx

```

Try it online!

Takes input from `STDIN`, outputs to `STDOUT`. Very straightforward implementation: does a regexp match for triple characters, deletes the last one, and loops until it didn't find anything else.

# Answer
> 0 votes
# Bash \+ GNU sed, 18 bytes

```
sed -es/{a..z}//3g

```

Try it online!

Way better than my pure `sed` answer. I marked it as `GNU sed` because POSIX `sed` doesn't define the result of supplying both a number and `g` as flags to the `s` command. `GNU sed`, as an extension, takes this to mean "replace all matches starting with the third", which is just what we want.

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
ʒIN£y¢!

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Unicode), 19 bytes

```
{⍵/⍨i∨≠0@(⍸i←≠⍵)⊢⍵}

```

Try it on TryAPL (because this doesn't work in TIO)

is the unique mask function when used monadically. It returns an array of ones and zeroes (ones where the first occurrence of an element is found, zeroes where there are duplicates). `i ← ≠⍵` assigns the unique mask of  (the argument to this function) to `i`.

`i` gives us ones where the first occurrence of each element is found, but we also need ones where the second occurrence of each element is found. To do that, we use  again, but first we clear all the unique elements from .  tells us the indices of the ones in its argument, so `⍸i` gives the indices of unique elements in ⍵. `(0 @ (⍸i)) ⍵` replaces the elements in  at these indices to 0 (so now they're all duplicates, and they don't conflict with the other lowercase letters in ). Running  on that gives ones where the second occurrence of each element is, along with a one as the first element.

(or) combines these two masks so there are zeroes only at the indices where triplicates are. `/` is can take a mask on its left and keep only the elements in its right argument that correspond to a 1 in the mask.  just swaps its order so we don't need parentheses.

# Answer
> 0 votes
# Jelly, 7 bytes

```
Ġḣ€2FṢị

```

Try it online!

A byte longer than Dennis' but a unique approach as far as I can tell

## How it works

```
Ġḣ€2FṢị - Main link. Takes a string s on the left
Ġ       - Group the indices of s by their values
  €     - Over each group:
 ḣ 2    -   Take the first 2
    F   - Flatten
     Ṣ  - Sort
      ị - Index back into s

```

# Answer
> -4 votes
# TCC, ~~5~~ 4 bytes

```
$~;2

```

Try it online!

```
     | Print (implicit)
$~   | Limit char occurence
     | of input (assumed if not given)
  ;  | seperator
   2 | to 2

```

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