# Question
Title: Remove Spaces, Maintaining Capitalization
Your input will be an English sentence, phrase, or word. It will only contain `a-zA-Z' -,.!?`. Your task is to take the input, remove spaces, and then redistribute capitalization such that letters at indexes that were capitalized before (and only letters at indexes that were capitalized before) are capitalized.

For example, if the input is `A Quick Brown Fox Jumped Over The Lazy Dog`, the (0-based) indexes of the capital letters are `0, 2, 8, 14, 18, 25, 30, 34, 39`. Next, remove spaces from the input: `AQuickBrownFoxJumpedOverTheLazyDog`. Next, lowercase all letters, but uppercase those at `0, 2, 8, 14, 18, 25, 30, 34, 39`: `AqUickbrOwnfoxJumpEdovertHelazYdog`, which is your output.

# Input

Your input will be an English sentence, phrase, or word. It can only contain lowercase letters, uppercase letters, hyphens, apostrophes, commas, periods, question marks, exclamation marks, and spaces.

# Output

The input with spaces removed, lowercase-d, with letters at the index of capital letters in the input uppercase-d.

NOTE: Your program cannot crash (error such execution terminates) with an IndexOutOfRange or similar error.

# Test Cases

```
Hi! Test!
Hi!tEst!

A Quick Brown Fox Jumped Over The Lazy Dog
AqUickbrOwnfoxJumpEdovertHelazYdog

testing TESTing TeStING testing testing TESTING
testingtESTIngteStInGTEstingtestingtestiNG

TESTING... ... ... success! EUREKA???!!! maybe, don't, NOOOOO
TESTING.........success!eureKA???!!!maybe,don't,nooooo

Enter        PASSWORD ---------
Enterpassword---------

A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Z z
AabbCcddEeffGghhIijjKkllMmnnOoppQqrrSsttUuvvWwxxZz

  TEST
teST

```

# Answer
> 8 votes
# Jelly, ~~14~~ 13 bytes

```
nŒlTɓḲFŒlŒuṛ¦

```

Try it online!

### How it works

```
nŒlTɓḲFŒlŒuṛ¦  Main link. Argument: s (string)

 Œl            Convert s to lowercase.
n              Perform character-wise "not equal" comparison.
   T           Get the indices of all truthy elements, i.e., the indices of all
               uppercase letters in s. Let's call the resulting array J.
    ɓ          Begin a dyadic chain with left argument s and right argument J.
     ḲF        Split s at spaces and flatten, removing the spaces.
       Œl      Convert s to lowercase.
            ¦  Sparse application:
         Œu        Convert s to uppercase.
           ṛ       Take the resulting items of the uppercased string at all indices
                   in J, the items of the lowercased string at all others.

```

# Answer
> 14 votes
# C (gcc), ~~82~~ ~~79~~ ~~74~~ ~~72~~ ~~69~~ ~~67~~ 66 bytes

```
f(c){for(char*s=c,*p=c;c=*s++;c&&putchar(c^(*p++|~c/2)&32))c&=95;}

```

Try it online!

# Answer
> 7 votes
# Python 2, 114 bytes

```
x=input()
X=x.replace(' ','')
print''.join([X[i].upper()if x[i].isupper()else X[i].lower()for i in range(len(X))])

```

Try it online!

# Equivalently:

# Python 2, 114 bytes

```
lambda x:''.join([[str.lower,str.upper][x[i].isupper()](x.replace(' ','')[i])for i in range(len(x)-x.count(' '))])

```

Try it online!

# Answer
> 7 votes
# Python 3, ~~78~~ ~~75~~ 72 bytes

```
s=input()
for c in s:s=s[c>' '!=print(end=(c+c).title()[s<'@'or'['<s]):]

```

*Thanks to @xnor for golfing off 6 bytes!*

Try it online!

# Answer
> 5 votes
# 05AB1E, ~~15~~ 14 bytes

-1 byte thanks to Emigna

```
ðKuvy¹Nè.lil}?

```

Try it online!

```
ðK             # Remove spaces
  u            # Convert to uppercase
   vy          # For each character...
     ¹Nè       #   Get the character at the same index from the original input
        .lil}  #   If it was a lowercase letter change this one to lowercase
             ? # Print without a newline

```

# Answer
> 5 votes
## Haskell, ~~98~~ ~~95~~ ~~89~~ ~~88~~ 81 bytes

*Thanks to @name, @nimi, @Zgarb, and @Laikoni for helping shave off 14 bytes total*

```
import Data.Char
\s->zipWith(\p->last$toLower:[toUpper|isUpper p])s$filter(>' ')s

```

Ungolfed:

```
import Data.Char
\sentence -> zipWith (\oldChar newChar ->
                        if isUpper oldChar
                        then toUpper newChar
                        else toLower newChar)
                     sentence
                     (filter (/= ' ') sentence)

```

# Answer
> 5 votes
# Python 2, 100 bytes

```
s=input()
print"".join([c.lower(),c.upper()][s[i].isupper()]for i,c in enumerate(s.replace(" ","")))

```

# Answer
> 4 votes
# , 24 bytes

```
ÄVuÓó
ejlDò/¥2lõ
vuk~òGd

```

Try it online!

These kind of challenges are exactly what V was made for. :)

Explanation:

```
Ä           " Duplicate this line
 Vu         " Convert it to lowercase
   Óó       " Remove all spaces
e           " Move to the end of this line
 j          " Move down a line (to the original)
  l         " Move one char to the right
   D        " And delete the end of this line
    ò       " Recursively:
     /      "   Search for:
         õ  "     An uppercase character
      ¥2l   "     On line 2
            "     (This will break the loop when there are no uppercase characters left)
vu          "   Convert it to lowercase
  k         "   Move up a line
   ~        "   Convert this to uppercase also
    ò       " Endwhile
     G      " Move to the last line
      d     " And delete it

```

# Answer
> 4 votes
# JavaScript (ES6), ~~94~~ ~~91~~ ~~85~~ ~~84~~ 81 bytes

```
s=>s.replace(r=/./g,c=>1/c?"":c[`to${r<s[x]&s[x++]<{}?"Upp":"Low"}erCase`](),x=0)

```
* 6 bytes saved with assistance from ETHproductions & Arnauld.
* 3 bytes saved thanks to l4m2

Try it online!

# Answer
> 3 votes
# Python 3, 117 114 98 bytes

```
s=input()
i,*y=0,*s.replace(' ','').lower()
for c in y:print(end=[c,c.upper()]['@'<s[i]<'[']);i+=1

```

Try It Online!

**Edit:** 3 bytes saved by UndoneStudios.

**Edit:** 14 bytes saved by Unrelated String.

This is pretty much my first code golf, so it's likely to be bad, minus help from comments below!

P.S. Yes, it's dumb that defining and incrementing `i` saves bytes over range(len(y)). Oh well.

---

# Python 3, 85 bytes

```
lambda s:''.join([c,c.upper()]['@'<b<'[']for b,c in zip(s,s.replace(' ','').lower()))

```

Try It Online!

This solution is entirely due to att; I'm keeping it separate because the strategy seems to me to have changed enough.

# Answer
> 3 votes
# Retina, ~~77~~ 71 bytes

```
.+
$&¶$&
T`L `l_`.+$
+`((.)*)[A-Z].*(¶(?<-2>.)*)
$1$3
.+¶

T`l `L_` .?

```

Try it online! Link includes test suite. Explanation: The first stage duplicates the line while the second stage lowercases the duplicate and deletes its spaces. The third stage then loops through each uppercase letter from right to left and attempts to place a space before the corresponding character on the second line. The first line is deleted and the spaces are used to uppercase the relevant characters of the result. Edit: Saved 6 bytes thanks to @Kobi.

# Answer
> 3 votes
# Alice, 32 bytes

```
/..- ~l+u~mSloy
\ia''-y.'Qa.+a@/

```

Try it online!

## Explanation

This is a standard template for programs that work entirely in ordinal mode. Unwrapped, the program is as follows:

```
i.' -l.uQm.lay.a-'~y+'~aS+o@

i       take input as string
.       duplicate
' -     remove spaces from copy
l.u     create all-lowercase and all-uppercase versions
Q       reverse stack, so original string is on top
m       truncate original string to length of spaces-removed string
.lay    convert everything except uppercase characters to \n
.a-'~y  convert everything except \n (i.e., convert uppercase characters) to ~
+       superimpose with lowercase string
        \n becomes the corresponding lowercase character, and ~ remains as is
'~aS    convert ~ to \n
+       superimpose with uppercase string
        lowercase in existing string stays as is because it has a higher code point
        \n becomes corresponding uppercase character
o       output
@       terminate

```

# Answer
> 3 votes
# Java 8, ~~184~~ ~~177~~ 161 bytes

```
s->{String r="";for(int i=0,j=i,t,u;i<s.length;){t=s[i++];if(t>32){u=s[j++];r+=(char)(t<65|t>90&t<97|t>122?t:u>64&u<91?t&~32:u>96&u<123|u<33?t|32:t);}}return r;}

```

Can definitely be golfed some more..
\- 16 bytes thanks to *@OlivierGrégoire* by taking the input as `char[]` instead of `String`.

**Explanation:**

Try it here.

```
s->{                           // Method with char-array parameter and String return-type
  String r="";                 //  Result-String
  for(int i=0,j=i,t,u;         //  Some temp integers and indices
      i<s.length;){            //  Loop over the String
    t=s[i++];                  //   Take the next character and save it in `t` (as integer)
                               //   and raise index `i` by 1
    if(t>32){                  //   If `t` is not a space:
     u=s[j++];                 //   Take `u` and raise index `j` by 1
     r+=                       //   Append the result-String with:
      (char)                   //    Integer to char conversion of:
       (t<65|t>90&t<97|t>122?  //     If `t` is not a letter:
        t                      //      Simply use `t` as is
       :u>64&u<91?             //     Else if `u` is uppercase:
        t&~32                  //      Take `t` as uppercase
       :u>96&u<123|u<33?       //     Else if `u` is lowercase or a space:
        t|32                   //      Take `t` as lowercase
       :                       //     Else:
        t);                    //      Take `t` as is
    }
  }                            //  End of loop
  return r;                    //  Return result-String
}                              // End of method

```

# Answer
> 3 votes
# Java (JDK), 84 bytes

```
s->{int j=0,c;for(var k:s)if((c=k&95)>0)System.out.printf("%c",c^(s[j++]|~c/2)&32);}

```

Try it online!

# Credits :

* Dennis for the bit twiddling as it's a good way to shorten the answer
* Fhuvi for trimming 12 bytes.

# Answer
> 3 votes
# Perl, ~~95~~ 94 + 1 = 95 bytes

+1 byte penalty for -n

Save one byte by replace from `s/\s//g` to `s/ //g`

```
$s=$_;s/ //g;$_=lc($_);while(/(.)/gs){$p=$&;$p=uc($p)if(substr($s,$-[0],1)=~/[A-Z]/);print$p;}

```

Try it online!

Explanation:

1. Make copy of input string.
2. Remove all spaceses and transform string to lower case.
3. Then start loop over each letter. Test letter in same position in saved string for upper case. If it upper - make current letter captitalized. Print letter.

Note that perl need to be run with "-n" command line switch

# Answer
> 2 votes
# MATL, 18 bytes

```
kXz"@GX@)tk<?Xk]&h

```

Same approach as Riley's 05AB1E answer.

Try it online!

# Answer
> 2 votes
# C# (.NET Core), 108 101 bytes

```
using System.Linq;s=>s.Replace(" ","").Select((c,i)=>s[i]>64&s[i]<91?char.ToUpper(c):char.ToLower(c))

```

Try it online!

* 7 bytes saved after realizing that the `char` class has static `ToUpper()` and `ToLower()` methods.

# Answer
> 2 votes
# Charcoal, 33 bytes

```
Ａ⁰χＦＬθ¿⁼§θι Ａ⁺¹χχ¿№α§θ⁻ιχ↥§θι↧§θι

```

Try it online!

As I still don't know how to pass a string with whitespaces as a single input parameter into Charcoal code, I just assign in the header the test string to the Charcoal variable that represents what would be the first input (`θ`):

```
ＡA Quick Brown Fox Jumped Over The Lazy Dogθ

```

So the code has the same number of bytes as if the string were passed as first input.

You can see here the verbose version of the code.

# Answer
> 2 votes
# PHP, 181 bytes

I try get the minor numbers of bytes,this is my code:

```
<?php
$s=readline();
preg_match_all('/[A-Z]/',$s,$m,PREG_OFFSET_CAPTURE);
$s=strtolower(str_replace(' ','',$s));
while($d=each($m[0]))$s[$d[1][1]]=strtoupper($s[$d[1][1]]);
echo $s;

```

Try it online!

# Answer
> 2 votes
# Common Lisp, 104 bytes

```
(defun f(s)(map'string(lambda(x y)(if(upper-case-p x)(char-upcase y)(char-downcase y)))s(remove #\  s)))

```

Try it online!

Unusually short for the wordy Common Lisp!

Straightforward code:

```
(defun f (s)                     ; receive the string as parameter
  (map 'string                   ; map the following function of two arguments
       (lambda (x y)             ; x from the original string, y from the string with removed spaces
         (if (upper-case-p x)    ; if x is uppercase
             (char-upcase y)     ; get y uppercase
             (char-downcase y))) ; else get y lowercase
       s
       (remove #\  s)))

```

# Answer
> 2 votes
# Google Sheets, 213 bytes

```
=ArrayFormula(JOIN("",IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Z]"),MID(UPPER(SUBSTITUTE(A1," ","")),ROW(OFFSET(A1,0,0,LEN(A1))),1),MID(LOWER(SUBSTITUTE(A1," ","")),ROW(OFFSET(A1,0,0,LEN(A1))),1))))

```

Input is in cell `A1` and the formula breaks down like this:

* `ArrayFormula()` lets us evaluate each term of `ROW()` independently
* `JOIN()` concatenates all those independent results into a single string
* `IF(REGEXMATCH(),UPPER(),LOWER()` is what makes it alternate using upper or lower case depending on what the case was at that position in the input
* `ROW(OFFSET())` returns an array of values `1` to `A1.length` that can be fed into the `MID()` function so we can evaluate each character in turn

Results of test cases: (It's easier to read if you click though to the larger version.)

# Answer
> 2 votes
# Ruby, 80 bytes

```
->a{n=a.downcase.delete' '
n.size.times{|i|(?A..?Z)===a[i]&&n[i]=n[i].upcase}
n}

```

Try it online!

# Answer
> 2 votes
# Perl, 92 bytes

```
$p[$i++]=$-[0]while s/[A-Z]/lc($&)/e;s/\s//g;for$c(@p){substr($_,$c,1)=~tr[a-z][A-Z]};print;

```

**Explanation:**

```
$p[$i++]=$-[0]while s/[A-Z]/lc($&)/e;   #get locations of caps into an array at the same time converting letters to lowercase

s/\s//g;   #delete all spaces

for$c(@p){substr($_,$c,1)=~tr[a-z][A-Z]};   #convert lowercase letters to uppercase where uppercase letters were present

print;   # print (of course) :)

```

# Answer
> 2 votes
# Perl 5, 40 bytes

37 bytes of code + `-F` flag. (note that on old versions of Perl, you might need to add `-an` flags)

```
print$F[$i++]=~/[A-Z]/?uc:lc for/\S/g

```

Try it online!

Explanations:
Thanks to `-F`, `@F` contains a list of every characters of the input.
`for/\S/g` iterates over every non-space character of the input. We use `$i` to count at which iteration we are. If `$F[$i++]` is an uppercase character (`/[A-Z]/`), then we print the uppercase current character (`uc`), otherwise, we print it lowercase (`lc`). Note that `uc` and `lc` return their argument unchanged if it isn't a letter.

---

Previous version (less golfed: 47 bytes):

```
 s/ //g;s%.%$_=$&;$F[$i++]=~/[A-Z]/?uc:lc%ge

```

Try it online!

# Answer
> 2 votes
# Charcoal, 18 bytes

```
⪫Ｅ⪫⪪θ ω⎇№α§θκ↥ι↧ιω

```

Try it online! Link is to verbose version of code. Explanation:

```
    θ               Input string
   ⪪                Split on spaces
  ⪫   ω             Join together
 Ｅ                  Loop over each character
          §θκ       Get character from original string
        №α          Search uppercase letters
       ⎇            If true (nonzero)
             ↥ι     Uppercase the current character
               ↧ι   Else lowercase the current character
⪫                ω  Join together
                    Implicitly print

```

The recent addition of StringMap shaves off a couple of bytes:

```
⭆⪫⪪θ ω⎇№α§θκ↥ι↧ι

```

is roughly equivalent to `⪫Ｅ`...`ω`.

# Answer
> 2 votes
# GNU sed, 67 + 1 = 68 bytes

+1 byte for `-r` flag.

```
:A
s/$/;/
:
s/([A-Z]);(.?)/;\l\1\u\2/
t
s/(\S);/;\1/
t
s/ ;//
/ /bA

```

Try it online!

## Explanation

The algorithm is pretty simple:

1. Insert a cursor (`;`) at the end of the line:

```
:A
s/$/;/
:

```
2. If the character before the cursor is an uppercase letter, lowercase it (`\l`) and uppercase the character after the cursor (`\u`), moving the cursor to the left, and branch back to `:`

```
s/([A-Z]);(.?)/;\l\1\u\2/
t

```
3. Otherwise, if the character before the cursor is *not* a space, move the cursor to the left and branch back to `;`:

```
s/(\S);/;\1/
t

```
4. Otherwise, if the cursor is preceded by a space, delete both:

```
s/ ;//

```
5. Finally, if there are any spaces left, branch back to `:A`:

```
/ /bA

```

# Answer
> 2 votes
# Rust, 143 bytes

```
|s|str::to_lowercase(s).replace(' ',"").chars().zip(s.chars()).for_each(|(c,d)|print!("{}",if d.is_uppercase(){c.to_ascii_uppercase()}else{c}))

```

Try it online!

Ungolfed:

```
  |input: &str|
    input.to_lowercase()          // create lowercase string
         .replace(' ', "")        // remove all spaces
         .chars()                 // iterate over characters
         .zip(input.chars())      // zip with input character iterator
         .for_each(|(c, input_c)| // for each character in both strings:
           print!("{}",                  // print the following:
             if input_c.is_uppercase() { // if the input character is uppercase
               c.to_ascii_uppercase()    // `c` in uppercase
             }
             else { c }                  // else `c`
           )
         )

```

# Answer
> 2 votes
# Go, 184 bytes

```
import(."strings";u"unicode")
func f(s string)string{S:=[]rune(ReplaceAll(ToLower(s)," ",""))
for i:=range s{if i<len(S)&&u.IsUpper(rune(s[i])){S[i]=u.ToUpper(S[i])}}
return string(S)}

```

Attempt This Online!

# Answer
> 2 votes
# Noulith, 88 bytes

```
\s->(for(p<<-s.lower filter (!=' '))yield if(s[p[0]].is_upper)p[1].upper else p[1])join""

```

Try it online!

# Answer
> 1 votes
# C, 103 bytes

```
i,j,c;f(char*s){for(i=j=0;c=tolower(s[j++]);)c-32&&putchar(c-32*(s[i]>64&&s[i]<91&&c>96&&c<123))&&++i;}

```

Try it online!

# Answer
> 1 votes
## **Python 3, ~~125~~, 124 bytes**

```
lambda s:''.join(c.upper()if i in(s.find(q)for q in s if q.isupper())else c for i,c in enumerate(s.replace(' ','').lower()))

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~106~~ 105 bytes

```
s=input()
print''.join(map(lambda(c,u):[c.lower,c.upper][u](),zip(s.replace(' ',''),map(str.isupper,s))))

```

Edit: save one byte via `print ''.join` =\> `print''.join`.

# Lambda form, 99 bytes

```
lambda s:''.join(map(lambda(c,u):[c.lower,c.upper][u](),zip(s.replace(' ',''),map(str.isupper,s))))

```

# Answer
> 1 votes
# SCALA, 128 chars, 128 bytes

```
var l=s.toLowerCase().filter(x=>x!=32)
for(i<-0 to l.size-1){if(s(i).isUpper)l=l.substring(0,i)+l(i).toUpper+l.substring(i+1)}
l

```

Thanks for this challenge. Try it online!

# Answer
> 1 votes
# q/kdb+, 49 bytes

**Solution:**

```
{@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}

```

**Examples:**

```
q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"Hi! Test!"
"Hi!tEst!"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"A Quick Brown Fox Jumped Over The Lazy Dog"
"AqUickbrOwnfoxJumpEdovertHelazYdog"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"testing TESTing TeStING testing testing TESTING"
"testingtESTIngteStInGTEstingtestingtestiNG"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"TESTING... ... ... success! EUREKA???!!! maybe, don't, NOOOOO"
"TESTING.........success!eureKA???!!!maybe,don't,nooooo"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"Enter        PASSWORD ---------"
"Enterpassword---------"

q){@[a;(&)(#:[a:lower x except" "]#x)in .Q.A;upper]}"A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Z z"
"AabbCcddEeffGghhIijjKkllMmnnOoppQqrrSsttUuvvWwxxZz"

q){@[a;(&)#:[a:lower x except" "]#x in .Q.A;upper]}"  TEST"
"teST"

```

**Explanation:**

Find indices where input is uppercase and then apply function `upper` to those indices on a lowercase, space-removed version of the input string. Note that we cannot apply the function beyond the length of the string, so use take (`#`) to truncate the input string to length of the lowercase, space-removed version.

```
{@[a;where count[a:lower x except " "]#x in .Q.A;upper]} / ungolfed
{                                                      } / lambda function
 @[ ;                                           ;     ]  / apply FUNC to VAR at INDICES: @[VAR;INDICES;FUNC]
                                                 upper   / uppercase, upper["abc"] -> "ABC"
                                       x in .Q.A         / boolean list where input is in uppercase alphabet ABC..XYZ
                                      #                  / take this many elements from list on the right (ie truncate)
           count[                    ]                   / returns length of the stuff inside the brackets, count["ABC"] -> 3
                         x except " "                    / remove " " from string
                   lower                                 / lowercase, lower["ABC"] -> "abc"
                 a:                                      / save in variable a
     where                                               / returns indices where true where[101b] -> 0 2
   a                                                     / our lowercased, space-stripped input

```

**Bonus:**

After reading the answers, thought I'd try a solution where I iterate over the input, so far I've only managed a 53 byte solution:

```
{a{$[y in .Q.A;upper x;x]}'#:[a:lower x except" "]#x}

```

# Answer
> 1 votes
## Swift 3.0, 199 bytes

```
var s="AS Ff",i=[String](),p=[Int](),j=0;for c in s.characters{if c>="A"&&c<="Z"{p.append(j)};if c != " "{i.append(String(c).lowercased())};j=j+1};for c in p{i[c]=i[c].uppercased()};print(i.joined())

```

Try it Online!

# Answer
> 1 votes
# PHP, 110 bytes

```
$q=strtr($s=$argn,[' '=>'']);foreach(str_split($s)as$k=>$v)echo$v<lcfirst($v)?ucfirst($q[$k]):lcfirst($q[$k]);

```

## Breakdown

```
$q=strtr($s=$argn,[' '=>''])

```

We take our input (`$argn`) and store it in a smaller variable because we need it later, before stripping out all the spaces with `strtr`

```
foreach(str_split($s)as$k=>$v)

```

We then take our original string, split it into an array of characters, and loop through each of them.

```
echo$v<lcfirst($v)?ucfirst($q[$k]):lcfirst($q[$k])

```

We check to see if the current letter is uppercase (`A` is less than `a` probably because ASCII), and echo out the corresponding letter from the space-stripped string with the appropriate case.

# Answer
> 1 votes
# Jelly, 11 bytes

```
ŒlðḲFŒuT}¦n

```

Try it online!

Just a restructuring of Dennis' original solution to avoid repeating `Œl`.

```
Œl             Lowercase the input.
  ð            Make that the left argument to the following dyadic chain.
   Ḳ           Split on spaces,
    F          flatten out the splits,
     Œu        then uppercase that
       T}¦     at the indices where
Œlð       n    the lowercase doesn't equal the original.

```

# Answer
> 1 votes
# Vyxal, 4 bytes

```
ȧ⇩$•

```

Try it Online!

Helps to have a "with capitalisation of" built-in

## Explained

```
ȧ⇩$•
ȧ     # Remove whitespace from the input
 ⇩    # and lowercase it
  $•  # Transfer the capitalisation of the original input to the stripped input.
# The reason for `•` doing this is because on lists, `•` is mould. Therefore, the idea was that it "moulds" one string to the capitalization of the other

```

Created with the help of Luminespire.

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


title: Bubbler and 3 others are typing․․․

text:
# Question
Title: Bubbler and 3 others are typing․․․
## Task

Implement a kind of "some users are typing" system, which can be found in Discord and some other chat clients.

* If 1 user (say, Bubbler) is typing, output `Bubbler is typing...`
* If 2 users (say, Bubbler and user) are typing, output `Bubbler and user are typing...`
* If 3 or more users are typing (say, Bubbler, randomuser1, randomuser2, randomuser3), output `Bubbler and 3 others are typing...`

The input is a list of usernames (list of strings); single string with delimiters (symbols or newlines) is also allowed. The output is a single string. Always respect the order of the input usernames. A username can contain upper/lowercase letters, digits, and spaces. Both usernames and the entire input list are never empty.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
["Bubbler"] -> "Bubbler is typing..."
["no one"] -> "no one is typing..."
["HyperNeutrino", "user"] -> "HyperNeutrino and user are typing..."
["emanresu A", "lyxal", "Jo King"] -> "emanresu A and 2 others are typing..."
["pxeger", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
-> "pxeger and 10 others are typing..."
["10", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
-> "10 and 10 others are typing..."
["and", "are"] -> "and and are are typing..."
["is"] -> "is is typing..."
["Bubbler is typing", "is", "are", "and"]
-> "Bubbler is typing and 3 others are typing..."

```

# Answer
# Whython, ~~84~~ 77 bytes

```
f=lambda a,*b:a+f" {'and %s are'%b?'is'%b} typing..."?f(a,f"{len(b)} others")
```

Attempt This Online!

This is my first answer in Whython, a *horrible* modification of Python I made. Its only new feature so far is `?`, which is a short-circuiting exception \[mis-\]handling operator.

Here I use it to handle the case where there are more than 2 people typing: I recurse on the function `f` with a newly formatted second argument.

This answer also makes use of the (not Whython-specific) fact that you can `%`-format a string with a tuple of arguments, as long as it's the right number of arguments - and that number can also be `0` or `1` \- so both `" is"%()` and `" and %s are"%("second argument",)` work fine.

-7 bytes thanks to @ovs: by trying to format `and %s are` (which requires `b` to be of length 1), then trying to format `is` (which requires `b` to be empty), we can save some bytes by avoiding `len()`.
> 18 votes

# Answer
# Python 3, 89 bytes

```
lambda a,*b:a+f" {b and'and %s are'%[b[0],'%d others'%len(b)][len(b)>1]or'is'} typing..."

```

Try it online!

-2 bytes thanks to dingledooper
> 13 votes

# Answer
# Haskell, 94 bytes

```
g(a:x)=a++f x++" typing..."
f[]=" is"
f[x]=" and "++x++" are"
f l=f[show(length l)++" others"]

```

Try it online!
> 11 votes

# Answer
# Vyxal , 32 bytes

```
ḣ:[‛λ¬$ḣ[_?L‹‛÷„]‛λ½|_‛is]`Ȯ»...

```

Try it Online!

```
ḣ                                # Push the first item (first user) and the rest to the stack
                                 # The first item will remain on the bottom of the stack
 :[                      ]       # If the rest exists (More than one user)
   ‛λ¬$                          # Push 'and' under the rest
       ḣ                         # Push the first item (second user) and rest to the stack
        [       ]                # If the rest exists (≥3 users)
         _                       # Pop the second user
          ?L‹                    # Push the input's length, -1
             ‛÷„                 # Push 'others'
                 ‛λ½             # Push 'are'
                    |            # Otherwise (one user)
                     _‛is        # Pop the resulting empty list and push 'is'
                          `Ȯ»... # Push 'typing'
                                 # (ṡ flag) join stack by spaces)

```

36 bytes flagless.
> 8 votes

# Answer
# Pip, 52 bytes

```
[POgg?["and"#c?[#g"others"]b"are"]"is""typing..."]Js

```

(Or 50 bytes in Pip `-s`, which would use a flag to accomplish the same thing as the `Js` at the end.)

Takes the names as separate command-line arguments. Try it online!

### Explanation

One big list, with the exact contents depending on the number of inputs, joined on spaces:

```
[                   ; List containing:
  PO g              ;  Pop first element of g (the command-line args)
  g ?               ;  Is g still nonempty?
    [               ;   If so (multiple names case), list containing:
      "and"         ;    This string
      # c ?         ;    Is the third cmdline arg nonempty?
        [           ;     If so (more than 2 names case), list containing:
          # g       ;      Number of elements remaining in g
          "others"  ;      and this string
        ]
        b           ;     Otherwise (2 names case), second cmdline arg
      "are"         ;    and this string
    ]
    "is"            ;   Otherwise (single name case), this string
  "typing..."       ;  and this string
]
J s                 ; Join that list (including all sublists) on space

```
> 7 votes

# Answer
# Vim, ~~92~~ 89 bytes

```
:3,$s/.*/\=line('.')-1.' others'
:1s/\v(\n.+)+/\1
:2s/^/and
ois typing...<esc>:3s/is/are
V{J

```

Try it online!

### Explanation

```
:3,$s/.*/\=line('.')-1.' others'<cr>

```

On every line from line 3 to the end of the buffer (if they exist), replace the contents of the line with the line number minus 1 followed by the string  `others`.

```
:1s/\v(\n.+)+/\1<cr>

```

Beginning at (the end of) line 1, find 1 or more matches of a newline followed by some characters. Replace with the last (newline + characters) match.

```
:2s/^/and <cr>

```

Add `and`  at the beginning of line 2 (if it exists).

```
ois typing...<esc>

```

Open a new line after the cursor (which is always on the last line at the point) and insert `is typing...`.

```
:3s/is/are

```

If that new line was line 3, change `is` to `are` (if it was line 2, leave unchanged).

```
V{J

```

Enter visual line mode, select to the beginning of the buffer, and join lines (space-separated).
> 6 votes

# Answer
# , ~~113~~ 102 bytes

Or **\>=4.1, 95 bytes** by replacing the word `function` with `\`.

```
function(s,l=length(s)-1,`?`=paste)s[1]?"if"(l,"and"?"if"(l-1,l?"others",s[2])?"are","is")?"typing..."

```

Try it online!

It appears that `paste` chains nicely, so we can rename that to `?` and use like string addition (with convenient spaces).
> 6 votes

# Answer
# C (clang) with `-m32`, ~~151~~ ~~148~~ 144 bytes

* -3 thanks to ceilingcat
* -4 by changing the base index from 0 to -1

To try a different approach from the other C submission, only the list of strings is needed as input for this answer. To get the length of the list, the function is called recursively and output is printed as the function processes the list.

De-golfed:

```
   g(*s,i) { // type-punning 'char **' as 'int *'
      printf(
        ~i? // is this the first element?
          *s? // (first element) no: end of list?
            i? // (end of list) no: is this the second element?
              "": // (second element) no, don't print if there is only 1 element
              s[1]? // (second element) yes, are there only 2 elements?
                "": // no, don't print second element if there are more than 2
                " and %s": // yes, print second element
            i<2? // (end of list) yes: are there more than 2 elements?
              "": // no
              " and %d others": // yes, print summary
          *s, // (first element) yes: print first element
        *s?
          : // use string if not at end
          i); // otherwise use the list count

      *s?
        g(s+1,i+1): // continue processing list
        printf(" %s typing...", i<2? "is": "are");
   }

   f(s) { g(s,-1); } // initialize list count

```

```
g(*s,i){printf(~i?*s?i?"":s[1]?"":" and %s":i<2?"":" and %d others":*s,*s?:i);*s?g(s+1,i+1):printf(" %s typing...",i?"are":"is");}f(s){g(s,-1);}

```

Try it online!
> 5 votes

# Answer
# Jelly, 47 bytes

```
ḢɓL,“¥ṃkŒ»ƊḷḊ?“ and ”;;“@k»ʋ;“ is”$ḷ?ṭ⁹“Æʋ@1'ɼ»

```

Try it online!

Full program, as it uses Jelly's smash-printing and nilad dumping.

## How it works

```
ḢɓL,“¥ṃkŒ»ƊḷḊ?“ and ”;;“@k»ʋ;“ is”$ḷ?ṭ⁹“Æʋ@1'ɼ» - Main link. Takes a list of usernames U on the left
Ḣ                                               - Chop off the first username, B, and set U' to be U without its head
 ɓ                                              - Start a new dyadic link f(U', B)
                                   ?            - If:
                                  ḷ             -   U' is non-empty
                           ʋ                    - Then:
             ?                                  -   If:
            Ḋ                                   -     U' has more than one element
          Ɗ                                     -   Then:
  L                                             -     Take the length of U'
    “¥ṃkŒ»                                      -     Compressed string: " others"
   ,                                            -     Pair; [len(U'), " others"]
          ḷ                                     -   Else: Yield B
              “ and ”;                          -   Prepend " and "
                      ;“@k»                     -   Append " are"
                                  $             - Else:
                            ;“ is”              -   Append " is"
                                     ṭ⁹         - Tack all of this to the end of B
                                       “Æʋ@1'ɼ» - Unparseable nilad. Smash print the previous stuff, then print " typing..."

```
> 4 votes

# Answer
# JavaScript, 77 bytes

```
a=>a[0]+` ${(l=a.length-1)?`and ${l>1?l+' others':a[1]} are`:'is'} typing...`

```

Try it online!
> 4 votes

# Answer
# Ruby, ~~79 ...~~ 73 bytes

```
->a,*s{[a,s[0]?[:and,s[1]?[s.size,:others]:s,:are]:"is","typing..."]*" "}

```

Try it online!

Thanks ovs for -3 bytes
> 4 votes

# Answer
# Julia 1.0, 82 bytes

```
t=" typing..."
>(x)="$x is$t"
x>y="$x and $y are$t"
x>y...=x>"$(length(y)) others"

```

Try it online!

the names are expected as arguments of the function `>`, for example `>("Bubbler")`, `>("a","b","c")`

# Julia 0.7, ~~79~~ 75 bytes

```
!t=t[(L=end-1;1)]*" $(L<1?:is:"and $(L<2?t[2]:"$L others") are") typing..."

```

Try it online!
> 4 votes

# Answer
# Perl 5 \+ `-pl`, 61 bytes

Thanks to @Xcali for -2!

```
s;$; @{[!(@_=<>)?is:'and',$#_?@_.' others':@_,are]} typing...
```

Try it online!

## Explanation

The first name is implicitly stored in `$_` (via `-p`) so it's easy to just add to it a string consisting of a leading space and an in-line list `@{[...]}`, finishing with  `typing...` as that's always needed no matter what. The in-line list will be implicitly joined by `$"` (space), which allows use of some barewords, saving bytes for the quotes. The rest of the input (`<>`) is slurped into `@_` which, if it's non-empty, results in a list consisting of `'and'`, and if `$#_` is truthy (`$#_` is the last array index of `@_`, which will be `0` if there is only one entry), we use `@_` in a scalar context (which is the number of elements i n`@_`) concatenated with `' others'`, but if `@_` only contains one entry, add it as is. If `@_` is empty, we just add the bareword `is` to the in-line list.
> 4 votes

# Answer
## Excel, 100 bytes

```
=A1&IF(COUNTA(A:A)=1," is"," and "&(IF(COUNTA(A:A)=2,A2,COUNTA(A:A)-1&" others"))&" are")&" typing…"

```
> 4 votes

# Answer
# PHP, ~~94~~ 91 bytes

```
fn($a)=>"$a[0] ".($a[1]?'and '.($a[2]?count($a)-1 .' others':$a[1]).' are':is).' typing...'

```

Try it online!

Raw first try at it, probably still golfable. It's a pity PHP cannot handle concatenation or nested ternary conditions without brackets..

EDIT: 3 bytes saved with thanks to Dom Hastings and 640KB's suggestions!
> 4 votes

# Answer
## Prolog, ~~108~~ 135 bytes (of which 27 are spent on producing a string)

This was fun, although Prolog does not have very much scope for golfery. My first, unsubmitted, attempt tried to use Prolog's Directed Clause Grammar syntax, but I couldn't get that to be shorter.

IIRC the rules here on CoGoSO correctly, it is permitted to return a string, and not required to print it; so I'm returning in a variable (`O`), as is traditional in Prolog.

```
f([X|R],O):-g(R,P),flatten([X,P,typing],Q),atomics_to_string(Q,' ',O).
g([],is).
g(L,[and,C,are]):-L=[Y],C=Y;C=[N,others],length(L,N).

```

Legend to the one-letter variable names:

```
% X: first name
% R: Rest of the names
% L: Rest of the names, seen from g/2's perspective
% O: Output
% C: Company, i.e. a word list like '[and, Y]'.
% P: intermediate output: nested list of atoms (representing inner words)
% Q: intermediate result: flat list of atoms

```

Usage examples:

```
?- f([jan,piet,klaas,tjoris,korneel], O).
O = "jan and 4 others are typing"

?- f([jan,piet,klaas], O).
O = "jan and 2 others are typing"

?- f([jan,piet], O).
O = "jan and piet are typing"

?- f([jan], O).
O = "jan is typing"

```

Ungolfed:

```
f([X|MoreNames], Out) :-
    % InnerWords like 'is' or '[and, Y, are]'
    innerwords(MoreNames, InnerWords),
    % Flatten `[X, [and, [N others], are], typing]`
    % to `[X, and, N, others, are, typing]`
    flatten([X, InnerWords, typing], AllWords),
    % Turn it into a string. This is not a very Prolog thing to
    % do, but the challeng requests it, so here goes.
    atomics_to_string(AllWords, ' ', Out).

% No more others: produce 'is' for 'X is typing'.
innerwords([], is).

% One or more others
innerwords(MoreNames, [and, Company, are]) :-
    % MoreNames is a list of 1, s
    Company=Y, MoreNames=[Y] ;
    % If we reach here, there are 2+ others.
    % (Or our caller is wrongly asking for additional solutions,
    %  and getting wrong answers as a reward.)
    % [and, [N, others], are]
    Company=[N, others], length(MoreNames, N).

```
> 4 votes

# Answer
# Vyxal , ~~42~~ 41 bytes

```
ḢḢ[₌hL‹` ÷„`+"]` λ¬ `j`is λ½`⌈?L‹ḃi`Ȯ»...

```

Try it Online!

Lovely dictionary compression. 44 bytes flagless

## Explained

```
ḢḢ[₌hL‹` ÷„`+"]` λ¬ `j`is λ½`⌈?L‹ḃi`Ȯ»...
ḢḢ                                         # If the length of the input is > 2:
  [₌hL‹                                    #     Push the head of the input and the length of the input - 1
       ` ÷„`+                              #     and append the string " others" to that
             "                             #     and wrap both in a list
              ]                            # endif
               ` λ¬ `j                     # Join the top of the stack on " and "
                      `is λ½`⌈             # Push the list ["is", "are"]
                              ?L‹          # And push the lenght of the input - 1
                                 ḃi        # boolify it to make it 0 or 1 (this is basically just checking if the list length is 1) and index into the list
                                   `Ȯ»...  # Push "typing..." to the stack
                                           # The -ṡ flag joins the stack on spaces. Without it, you'd need `WṄ for +3 bytes.

```
> 3 votes

# Answer
# C (clang) `-m32`, ~~109~~ 107 bytes

*-2 thanks to ErikF!*

```
t(*n,l){printf(--l?l-1?"%s and %d others are%s":"%s and %s are%s":"%s is%3$s",*n,l-1?l:n[1]," typing...");}

```

Try it online! Takes input as an array of `char*` and its length.

# C (clang), ~~115~~ 108 bytes

*-7 thanks to ErikF!*

```
t(**n,l){printf(--l?l-1?"%s and %d others are%s":"%s and %s are%s":"%s is%3$s",*n,l-1?l:n[1]," typing...");}

```

Try it online! Takes input as an array of `char*` and its length.
> 3 votes

# Answer
# Rust, ~~185~~ ~~183~~ ~~162~~ 136 bytes

```
|v:&[&str]|[v[0],&match v.len(){1=>"is".into(),2=>format!("and {} are",v[1]),l=>format!("and {} others are",l-1)},"typing..."].join(" ")

```

Try it online!

Ungolfed:

```
|v: &[&str]| {
        [
            v[0],
            &match v.len() {
                1 => "is".into(),
                2 => format!("and {} are", v[1]),
                l => format!("and {} others are", l - 1),
            },
            "typing...",
        ]
        .join(" ")
    }

```

Log:

* -2 for excluding the closure name
* -21 for `v:&[&str]`, implicit return type, wildcard with binding, `s` removal, brackets. Thanks @AnttiP!
* -26 for removing redundant `"typing..."` occurrences and one `format!` use (by @Ezhik)
> 3 votes

# Answer
# Zsh, 67 bytes

```
x=(is "and $2 are")
echo $1 ${x[#]-and $[~-#] others are} typing...
```

Attempt This Online!

Looks up the correct format string into the array `$x` (one of `is`, `and $2 are`, or an unset variable), defaulting to `and $[~-#] others are` (where `$[~-#]` is `number of arguments - 1`), and prints that with the first input `$1` and the string `typing...`.

---

## Zsh, 79 bytes

```
T=\ typing...
1()<<<$1\ is$T
2()<<<"$1 and $2 are$T"
$# $@||2 $1 $[~-#]\ others
```

Attempt This Online!

* Defines two functions called `1` and `2` which print formatted messages for singular and plural, respectively
* Then it calls the function with the name `$#` (the number of arguments), so that if 1 or 2 people are typing, the correct message is printed
* If there are more than 2 arguments, the function call will fail, triggering the `||` branch
    + This calls `2` with the first argument and the string `$[~-#] others`
        - (It has to be `~-#`, because `#-1` doesn't work, although I don't really understand why)
> 3 votes

# Answer
# 05AB1E, 42 bytes

```
ćs©gĀi'€ƒ®ćsgĀi\Ig<'ˆ†]…is€™#Ig≠è“ÜÔ...“ðý

```

Try it online or verify all test cases.

**Explanation:**

```
ć                       # Extract head of the (implicit) input-list; pop and push
                        # remainder-list and first item separately
 s                      # Swap so the remainder-list is at the top
  ©                     # Store it in variable `®` (without popping)
   gĀi                  # Pop and if there are any strings left (2+ inputs):
      '€ƒ              '#  Push dictionary string "and"
         ®              #  Push list `®`
          ćs            #  Extract head and swap again
            gĀi         #  Pop and if there are any strings left (3+ inputs):
               \        #   Discard the head we've pushed
                Ig<     #   Push the input-length - 1
                   'ˆ† '#   Push dictionary string "others"
     ]                  # Close both if-statements
      …is€™             # Push dictionary string "is are"
           #            # Split it on spaces: ["is","are"]
            Ig          # Push the input-length
              ≠         # Check that it's NOT 1 (0 if 1; 1 otherwise)
               è        # Use that to index into the pair
      “ÜÔ...“           # Push dictionary string "typing..."
ðý                      # Join the entire stack with space delimiter
                        # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'€ƒ` is `"and"`; `'ˆ†` is `"others"`; `…is€™` is `"is are"`; and `“ÜÔ...“` is `"typing..."`.
> 3 votes

# Answer
# Retina 0.8.2, 63 bytes

```
^.*$
$& is
(¶.*){2,}
¶$#1 others
¶(.*)
 and $1 are
$
 typing...

```

Try it online! Takes newline-delimited input but test suite splits on commas for convenience. Explanation:

```
^.*$
$& is

```

Just one person is typing.

```
(¶.*){2,}
¶$#1 others

```

If there are at least two others then replace the list with a single element giving their count.

```
¶(.*)
 and $1 are

```

More than one person is typing.

```
$
 typing...

```

Complete the sentence.
> 3 votes

# Answer
# Charcoal, 48 bytes

```
Ｓ ＷＳ⊞υι¿υ«and ¿⊖Ｌυ⁺Ｌυ others⊟υ are»is¦ typing...

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings, which for some reason is golfier than taking input as a JSON list. Explanation:

Output the first name and a space.

```
ＷＳ⊞υι

```

Read in any other names.

```
¿υ«

```

If there were any, then:

```
and

```

Output `and`  (with a trailing space).

```
¿⊖Ｌυ

```

If there was more than one other, then...

```
⁺Ｌυ others

```

... concatenate the count to the string  `others` (with a leading space) and output that, otherwise...

```
⊟υ

```

... output the last (and only other) name.

```
 are

```

Output  `are` (with a leading space).

```
»is

```

Otherwise, output `is`.

```
 typing...

```

Output  `typing...` (with a leading space).
> 3 votes

# Answer
# Python3, 95 bytes:

```
lambda d:f'{d[0]} {"and "+[d[1],f"{l-1} others"][l>2]+" are"if(l:=len(d))>1else"is"} typing...'

```

This solution requires no pre-formatting of the input list (i.e no unpacking).
> 3 votes

# Answer
## Batch, 170 bytes

```
@if "%2"=="" echo %~1 is typing...&exit/b
@set s=%~1
@set t=%~2
@set n=2
:l
@if not "%3"=="" set t=%n% others&set/an+=1&shift&goto l
@echo %s% and %t% are typing...

```

Takes input as command-line parameters. Explanation:

```
@if "%2"=="" echo %~1 is typing...&exit/b

```

Handle the case of there only being one user.

```
@set s=%~1
@set t=%~2
@set n=2

```

Assume there are two users.

```
:l
@if not "%3"=="" set t=%n% others&set/an+=1&shift&goto l

```

While more users are found, update the number of others and increment the total number of users.

```
@echo %s% and %t% are typing...

```

Output the users or count as appropriate.
> 3 votes

# Answer
# BQN, 77 bytes

```
⊑∾" typing..."∾˜·(0<≠)◶⟨" is"⋄" and "∾" are"∾˜(1<≠)◶⟨⊑⋄" others"∾˜•fmt∘≠⟩⟩1⊸↓

```

Anonymous tacit function that takes a list of strings and returns a string. Run it online!

### Explanation

```
(0<≠)◶⟨" is"⋄...⟩1⊸↓
                 1⊸↓  Drop the first element of the argument list
(   )◶                Choose, based on the result of this function:
   ≠                     Length of the remaining list
 0<                      is greater than 0? (1 if so, 0 if not)
      ⟨         ⟩      one of these functions:
       " is"             Return that string
            ⋄         or...

" and "∾" are"∾˜(1<≠)◶⟨⊑⋄...⟩
                (   )◶         Choose, based on the result of this function:
                   ≠              Length of the all-but-the first list
                 1<               is greater than 1?
                       ⟨     ⟩  one of these functions:
                        ⊑         First element of the all-but-the-first list
                         ⋄     or... (see below)
        " are"∾˜               Append that string to the result
" and "∾                       Prepend that string to the result

" others"∾˜•fmt∘≠
                ≠  Length of the all-but-the-first list
           •fmt∘   Format as string
" others"∾˜        Append that string to the result

⊑∾" typing..."∾˜·...
                  ...  Calculate all of the above
                 ·     and then
   " typing..."∾˜      Append that string to the result
⊑∾                     Prepend the first element of the argument list

```
> 3 votes

# Answer
# JavaScript, ~~85~~ 82 bytes

```
a=>(b=a.length,a[0]+(b<2?" is":` and ${b<3?a[1]:b-1+" others"} are`)+" typing...")

```

Try it online!
> 2 votes

# Answer
# jq, ~~99~~ 99+1 (-r flag penalty) = 100 bytes

```
(length-1)as$l|.[0]as$n|["is","and \(.[1]) are"]|"\($n) \(.[$l]//"and \($l) others are") typing..."

```

Try it online!

I'm pretty sure there's room to golf this more, but not tonight. :)

1. Stash the length of the input list in `$l`. stash the first element in \`$n

`(length-1)as$l|.[0]as$n`
2. Generate a new list consisting of two elements, `is` and `is 2nd-input-list-entry are`

`|["is","and \(.[1]) are"]`
3. Print the first input list name, then index the list from step 2 by the number of entries in the input minus 1. The `//` code is called if the index doesn't exist. In that case the alternate text `and length-of-input-minus-1 are` is used. The `typing...` string is appended regardless of what other choices were made.

`|"\($n) \(.[$l]//"and \($l) others are") typing..."`
> 2 votes

# Answer
# Dart, 101 Bytes

```
f(a)=>a[0]+(a.length>1?" and ${a.length>2?"${a.length-1} others":"${a[1]}"} are" : " is")+" typing.";

```

Try it online
> 2 votes

# Answer
# Python 2, 102 bytes

```
i=input()
l=len(i)
print(i[0]+" and "+[`l-1`+" others",i[-1]][l<3]+" are",i[0]+" is")[l<2],"typing..."

```

Try it online!

Simple nested list slices but takes advantage of no brackets required for printing in Python 2 and also the use of back ticks for the string conversion.
> 2 votes

# Answer
# Java, 93 bytes

```
a->a[0]+(a.length>1?" and "+(a.length>2?a.length-1+" others":a[1])+" are":" is")+" typing..."

```

Try it online!
> 2 votes

# Answer
# SimpleTemplate 0.84, 126 bytes

This full program expects a variable number of arguments passed to the `render()` method. Argument unpacking can be used for convenience. Each argument is 1 user.

```
{@echoargv.0}{@ifargc is1} is{@else} and {@ifargc is2}{@echoargv.1}{@else}{@set-T argc,1}{@echoT} others{@/} are{@/} typing...

```

This will output the text into the standard output, by default.

---

## Ungolfed:

To make it easier to understand, here's an ungolfed version of the code above:

```
{@echo argv.0}

{@if argc is 1}
    {@echo " is"}
{@else}
    {@echo " and "}

    {@if argc is 2}
        {@echo argv.1}
    {@else}
        {@set- count argc, 1}
        {@echo count, " others"}
    {@/}

    {@echo " are"}
{@/}

{@echo " typing..."}

```

---

## About the language:

There are a few important things to keep in mind when reading the code.
This section is important, but code is importanter.

* All text that isn't part of an instruction, is just displayed as-is.

Newlines and all, except when what is to be displayed is just whitespace, which will be deleted by default.
* The variables `argv` and `argc` almost the same as the `$argv` and `$argc` variables in PHP, or `argv` and `argc` in C.

However, the first argument in `argv` is the first argument passed to the `render()` method of the compiler, instead of the name of the file.
* Whitespace handling is super loose, so, `{@echo 123}` and `{@echo123}` work the same. This helps saving a lot of space.
* The line `{@echo argv.0}` shows the syntax to access an array element.
This line is accessing the 1st 0-indexed element in the array `argv`.
* The line `{@set- count argc, 1}` looks weird.
All it does is to set the the variable `count` to the value of `argc - 1`.

The `set-` (set minus) instruction does both operations in one.
This is the same as `{@set count argc}{@inc by -1 count}`, or `$argc = $count; $count += -1;`, but all in 1.
* The lines `{@if argc is <val>}` are verifying is `argc` is `<value>` (1 or 2, in this case).
Internally, this will verify if `argc` and `<value>` are identical, with the === operator.

---

## Running the code:

You can run the code on: http://sandbox.onlinephpfunctions.com/code/7233b0a3b8b2fd96924e054944e4ddc850c8f381

Please pick a version between 5.6 and 7.4.13. Can't fix the 8.0.0 compatibility issue without invalidating this answer.
> 2 votes

# Answer
# Julia, 116 bytes

```
f(l,s=length(l))=replace("x z typing...","x"=>l[1],"z"=>"$(s>1 ? "and $(s>2 ? "$(s-1) others" : l[2]) are" : "is")")

```

Note that this code does **not work with Julia 1.0**, thus I can not put it on Try it online. My test code in Julia 1.7 is as follows.

```
f(l,s=length(l))=replace("x z typing...","x"=>l[1],"z"=>"$(s>1 ? "and $(s>2 ? "$(s-1) others" : l[2]) are" : "is")")

a=["Bubbler"]
b=["no one"]
c=["HyperNeutrino", "user"]
d=["emanresu A", "lyxal", "Jo King"]
e=["pxeger", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
g=["10", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
h=["and", "are"]
k=["is"]
l=["Bubbler is typing", "is", "are", "and"]

println(f(a))
println(f(b))
println(f(c))
println(f(d))
println(f(e))
println(f(g))
println(f(h))
println(f(k))
println(f(l))

```

which produces the following output

```
Bubbler is typing...
no one is typing...
HyperNeutrino and user are typing...
emanresu A and 2 others are typing...
pxeger and 10 others are typing...
10 and 10 others are typing...
and and are are typing...
is is typing...
Bubbler is typing and 3 others are typing...

```

Maybe I can ask the developers of Try it online! to upgrade the Julia version.
> 2 votes

# Answer
# Python 3, ~~161~~ 136 bytes

```
x=input().split(",")
y=len(x)
if y==1:z="is",
if y==2:z="and",x[1],"are"
if y>2:z="and",len(x)-1,"others are"
print(x[0],*z,"typing...")

```

I FGITW faster.

Try it online!
> 1 votes

# Answer
# Pari/GP, 89 bytes

```
a->Str(a[1]if(#a<2," is",Str(" and "if(#a<3,a[2],Str(#a-1" others"))" are"))" typing...")

```

Try it online!
> 1 votes

# Answer
# Lua, 110 108 99 bytes

```
a,b,c=...print((b and a.." and "..(c and(#{...}-1 .." others")or b).." are"or a.." is").." typing")

```

Try it online!

Takes input from command-line arguments, prints to stdout.
> 1 votes

# Answer
# APL+WIN, 86 bytes

Prompts for the user list as a nested vector

```
(,(8⍴2)⊤175+18 4 0[3⌊⍴u])/u[1],('is' 'and'),(⊂↑1↓u),(⊂¯1+⍴u←⎕),'others' 'are' 'typing'

```

Try it online! Thanks to Dyalog Classic
> 1 votes

# Answer
# Python 3, 129 bytes

```
lambda u:(f"{(u[0])} is"if len(u)<2else f"{u[0]} and {u[1]} are"if len(u)<3else f"{u[0]} and {len(u)-1} others are")+" typing..."

```

Try it online!

A different approach that was much harder to write is 155 bytes :(

# Python 3, 155 bytes

```
lambda u:f"{u[0]} %s%s%s typing..."%(["and ",""][len(u)<2],""if len(u)<2else u[1]if len(u)<3else len(u)-1,[" are","is"][len(u)<2]+[""," others"][len(u)>2])

```

Try it online!
> 1 votes

# Answer
# TypeScript's type system, 147 bytes

```
//@ts-ignore
type F<A,B=A extends[{},...infer B]?B["length"]:0>=`${A[0]} ${B extends 0?"is":`and ${B extends 1?A[1]:`${B} others`} are`} typing...`

```

Try it at the TS playground!
> 1 votes

# Answer
# Uiua, 76 bytes

```
$"_ typing..."($"_ is"⊔⊢|/$"_ and _ are"|$"_ and _ others are":-1⊃⧻⊢)+1±-2⧻.

```

Test pad
> 1 votes

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


title: The many ways to skin a `cat`

text:
# Question
Title: The many ways to skin a `cat`
The well known `cat` command simply copies its stdin directly to stdout unchanged. But there are plenty of other commandline tools that exist...

What other commands can be used to duplicate the functionality of the venerable `cat`?

# Rules

1. You are not allowed to use any *shell* features, including pipes, file redirection, variables, etc.
2. Your answer can only *directly* invoke one command - e.g. `foo-cmd; bar` is disallowed because you are directly invoking both `foo-cmd` and `bar` (not to mention, the use of a semicolon breaks rule 1). However, commands that internally execute other commands (such as `xargs`) **are** allowed.
3. The command you use should already exist and be at least somewhat widely known. And an explanation of nontrivial answers would also be nice.
4. This contest is not about finding a single "best" cat implementation, and as such will not have a single accepted answer. Rather, this is an exercise in creativity: how many different ways can we collectively implement `cat`?

# Solutions

So far, we have a `cat` implementation for the following commands (add yours to the list when you answer):

# Answer
> 1 votes
# sed

```
sed ""

```

Plain old sed with an empty string.

# Answer
> 0 votes
# awk

```
awk '1{print}'

```

Explanation:

* `1` -\> match every line.
* `{print}` -\> for each matched line, print it

Or, more tersely:

```
awk 1

```

Here, a missing block implies `{print}`.

---
Tags: code-challenge, popularity-contest, bash
---