# Question
Title: Find the minimum and maximum integers in an array, without using builtins
## Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output *only* the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

## Example session

```
> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18

```

## Reference implementation

```
// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}

```

## Rules

* You may not use a built-in function to calculate the values.
* Standard loopholes disallowed.
* Creative implementations encouraged.
* This is , shortest answer wins but will not be selected.

## Clarifications

* If the array contains 1 element you need to output it twice.
* If the minimum and maximum values are the same, you need to output them both.

# Answer
# Jelly, 3 bytes

```
Ṣ.ị

```

Try it online!

Sort the array, and then takes the 0.5-th element.

Jelly uses 1-indexing, and floating points indexing means take its floor and its ceil.

So the 0.5-th element would give you the 0th element and the 1st element.

The 0th element is the last element.
> 29 votes

# Answer
# Python, ~~61~~ ~~49~~ ~~37~~ ~~36~~ ~~34~~ 31 bytes

```
lambda s:s.sort()or[s[0],s[-1]]

```

*-12 bytes thanks to RootTwo*

*Another -12 bytes thanks to chepner*

*-2 bytes thanks to johnLate*

*-3 bytes thanks to johnLate*
> 12 votes

# Answer
# Brain-Flak ~~220~~ 218 bytes

```
(({}))([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}({}<((())){{}{}([][()])}{}>)

```

Try It Online!

## Explanation

First it doubles the top value (in cast the list is only one long)

```
(({}))

```

Then it uses my bubble sort algorithm:

```
([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}

```

Then it picks up the top value of the stack (i.e. the min)

```
({}<...>)

```

Then it pops until the height of the stack is one:

```
((())){{}{}([][()])}{}

```
> 8 votes

# Answer
## JavaScript (ES6), 34 bytes

```
a=>[a.sort((x,y)=>x-y)[0],a.pop()]

```

`sort` sorts in-place, so I can just refer to the \[0\] index for the lowest value and `pop` the highest value from the array, however it does a string sort by default so I have to pass a comparator.
> 8 votes

# Answer
## Mathematica, 18 bytes

```
Sort[#][[{1,-1}]]&

```

Sorts the array and extracts the first and last values.
> 5 votes

# Answer
# R, 31 bytes

```
l=sort(scan());l[c(1,sum(l|1))]

```

Not *that* original, but hey !
> 5 votes

# Answer
# ARM Machine Code, 26 bytes

Hex dump (little endian):

```
6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770

```

This is a function, with no system call or library dependence. The encoding is Thumb-2, a variable (2 or 4 byte) encoding for 32-bit ARM. As one might imagine, there's no easy way to just sort and pick the first and last elements here. Overall there's nothing really that fancy going on here, it's more or less the same as the reference implementation.

Ungolfed assembly (GNU syntax):

```
.syntax unified
.text
.global minmax
.thumb_func
minmax:
    @Input: @r0 and r1 are dummy parameters (they don't do anything)
    @r2 - Pointer to list of integers (int*)
    @r3 - Number of integers to sort (size_t)
    @Output:
    @Minimum of the list in r0 (int)
    @Maximum in r1 (int)
    ldr r0,[r2] @min=r2[0]
    mov r1,r0 @max=min
    loop:
        @ip is intra-procedure call register, a.k.a. r12
        ldr ip,[r2],#4 @ip=*r2++
        cmp r0,ip
        it gt @if (r0>ip)
        movgt r0,ip @r0=ip
        cmp r1,ip
        it lt @if (r1<ip)
        movlt r1,ip @r1=ip
        subs r3,r3,#1
        bhi loop @while (--r3>0)
    bx lr @Return

```

Tested on the Raspberry Pi 3; here's the testing script (C99, input through argv):

```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//First 2 arguments are dummies.
uint64_t minmax(int,int,int* array,size_t size);

int main(int argc,char** argv) {
    int i;
    int array[argc-1];
    for (i=1;i<argc;i++) {
        array[i-1]=atoi(argv[i]);
    }
    uint64_t result = minmax(0,0,array,argc-1);
    printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32));
}

```
> 5 votes

# Answer
# Haskell, 27 bytes

```
f x=(`foldl1`x)<$>[min,max]

```

In Haskell, `min` and `max` give minimum and maximum of two arguments, not of a list. I couldn't tell whether this is disallowed (it seems that instead only `minimum` and `maximum` would be disallowed) so please let me know if they are and I'll promptly delete this answer.
> 4 votes

# Answer
# Octave, 20 bytes

```
@(n)sort(n)([1,end])

```

This sorts the input vector and outputs the first and last value.
> 3 votes

# Answer
## Actually, 5 bytes

```
S;F@N

```

Try it online!

Explanation:

```
S;F@N
S      sort
 ;     dupe
  F    first element
   @N  and last element

```
> 3 votes

# Answer
# 05AB1E, ~~6~~ 4 bytes

```
{Âø¬

```

**Explanation**

```
{     # sort list
 Â    # bifurcate
  ø   # zip
   ¬  # head

```

Try it online
> 3 votes

# Answer
# MATL, 4 bytes

```
S5L)

```

Try it online!

### Explanation

```
S    % Implicitly input the array. Sort
5L   % Push [1 0]. When used as a (modular, 1-based) index, this means "first and last"
)    % Apply as an indexing vector into the sorted array. Implicitly display

```
> 3 votes

# Answer
# Python, 29 bytes

```
lambda s:s[s.sort():1]+s[-1:]

```

Test it on Ideone.
> 3 votes

# Answer
# C, ~~83~~ ~~81~~ 79 bytes

```
m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;printf("%i %i",m,M);}

```
> 3 votes

# Answer
# POSIX Awk, 44 bytes

```
awk '{for(;NF-1;NF--)if($1>$NF)$1=$NF}1' RS=

```
> 2 votes

# Answer
# Brachylog, 9 bytes

```
oOtT,Oh:T

```

Try it online!
> 1 votes

# Answer
# Processing, ~~59~~ 52 bytes

```
void m(int[]x){x=sort(x);print(x[0],x[x.length-1]);}

```

Processing doesn't actually let me read from stdin that I've been able to find, and I don't know if its internal Java compiler supports lambdas (and its been so long since I've had to write serious Java that I don't remember how).
> 1 votes

# Answer
# , 12 bytes

```
:sor
ò2Gjkd

```

Try it online!

Credit to DJMcMayhem for this.
> 1 votes

# Answer
# CJam, ~~10~~ 9 bytes

```
q~$_(p;W>

```

Try it online.

I'm really not good at CJam.

```
q~          e# eval input
  $         e# sort
   _        e# duplicate
    (       e# pop first
     p      e# print
      ;     e# remove array
       W>   e# get last element

```
> 1 votes

# Answer
# Perl 6 13 bytes

```
*.sort[0,*-1]

```

## Test:

```
my &min-max = *.sort[0,*-1];

say min-max 1;
# (1 1)
say min-max (0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14)
# (-14 18)

```
> 1 votes

# Answer
## Python 2, 34 bytes

```
x=sorted(input());print x[0],x[-1]

```
> 1 votes

# Answer
# APL (Dyalog), ~~11~~ ~~10~~ 5 bytes

-5 thanks to Erik the Outgolfer.

According to the original poster, using *a function that picks the largest of exactly two elements (in contrast to the largest of a whole array)* \[is\] *allowed*. Therefore, the obvious solution is:

```
⌊/,⌈/

```

`⌊/` minimum-reduction

`,` followed by

`⌈/` maximum-reduction

---

More in the spirit of the challenge:

```
(⊃,⊢/)⍋⊃¨⊂

```

`(`

first

`,` followed by

`⊢/` the last (lit. right-reduction)

`)` of

the indices of the elements in ascending order

`⊃¨` each picks from

the entire argument

TryAPL online!
> 1 votes

# Answer
# PHP, 44 bytes

```
function a($a){sort($a);echo $a[0].end($a);}

```
> 1 votes

# Answer
## C++ (g++), ~~148 133 131 122~~ 119 bytes

```
#import<map>
#import<vector>
[](std::vector<int>v){int a=v[0],b=a;for(int i:v)i<a?a=i:i<b?:b=i;printf("%d %d\n",a,b);};

```

Try it online!
> 1 votes

# Answer
# PHP, ~~66~~ 65 bytes

Note: this doesn't use any `sort` builtin. Also, PHP 7 required for the null coalesce operator.

```
for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";

```

The `max` part is straightforward. The `min` part is a bit more elaborate. since in PHP `null` is less than `123`, null needs to be handled. For this I'm using the null coalesce operator. If `$l` is null, use the current number (`$x`) instead, then take the smaller of the 2 numbers.

Run like this:

```
php -d error_reporting=30709 -r 'for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo

```

# 37 bytes (with sort)

Being allowed to sort makes it trivial (windows-1252 encoding):

```
php -d error_reporting=30709 -r '$a=$argv;echo$a[sort($a)],~ß,end($a);' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo

```

Sort returns `1` when successful, and the list of arguments will start with `-` which will be sorted as the first item, so we need item `1` to yield `min`. Therefore we happen to be able to use the return value of `sort` as the index, saving 2 bytes.

# Tweaks

* Use `n|"0"` to make `"0"` truthy to continue the loop, instead of `0 ."0"`. Saved a byte
> 1 votes

# Answer
## Java, 115 bytes

```
String f(int[]i){int t=i[0],a=t,b=t;for(int c=0;c<i.length;c++){a=i[c]<a?i[c]:a;b=i[c]>b?i[c]:b;}return""+a+" "+b;}

```

Ungolfed:

```
String f(int[] i) {
    int t=i[0], a=t, b=t; // assigns a and b to i[0]
    for (int c=0; c < i.length; c++) { // loop through the array
        a=(i[c]<a) ? i[c] : a;
        b=(i[c]>b) ? i[c] : b; // assignment with ternary operator
    }
    return ""+a+" "+b; // returns a string
}

```

My first ever code "golf" solution.
> 1 votes

# Answer
## JavaScript (ES6), 68 58 bytes (without sorting)

Oh my first try in Golf: without explicit sort (and without min max).
Thanks to @ETHproductions for golfing tips!!

```
a=>(b=[],a.map(n=>b[n]=0),[b.indexOf(0),b.lastIndexOf(0)])

```

Does not work with negative integers.

Tried @Luis Mendo 's approach but got it 2 bytes longer... Cost for supporting negative numbers lol?

```
a=>[a.find(n=>a.every(e=>e>=n)),a.find(n=>a.every(e=>e<=n))]

```

Could get shorter if order of output is not important:

```
a=>a.filter(n=>a.every(e=>e>=n)||a.every(e=>e<=n))

```
> 1 votes

# Answer
# JavaScript (ES6), 46 bytes

I wanted to try an answer without sorting:

```
a=>a.map(i=>i<n?n=i:i>x?x=i:0,n=x=a[0])&&[n,x]

```

Bonus recursive version, 53 bytes:

```
f=([i,...a],n=i,x=i)=>i+.5?f(a,i<n?i:n,i>x?i:x):[n,x]

```
> 1 votes

# Answer
# Julia 0.6, 19 bytes

```
x->sort(x)[[1,end]]

```

Try it online!
> 1 votes

# Answer
## Haskell, 36 bytes

```
(\l->(head l,last l)).Data.List.sort

```

Would love to use `&&&` here but imports are so costly...
> 0 votes

# Answer
## Ruby, ~~38~~ 23 bytes

~~`def m(v) puts v.sort![0];$><<v[-1];end`~~

```
->v{[v.sort![0],v[-1]]}

```

Thanks @Jordan!
> 0 votes

# Answer
## Retina, 17 bytes

```
O#`
$
¶$`
Ss`¶.+¶

```

Input and output are linefeed-separated.

Try it online!

### Explanation

```
O#`

```

Sort lines by numerical value.

```
$
¶$`

```

Duplicate the entire input to make sure that the first and last element are distinct.

```
Ss`¶.+¶

```

Remove all intermediate lines, leaving only the minimum and maximum.
> 0 votes

# Answer
# BASH 38

```
grep -o '[^ ]*'|sort -g|sed -n '1p;$p'

```
> 0 votes

# Answer
# Factor, 38 bytes

```
[ natural-sort [ first ] [ last ] bi ]

```

Sort the sequence and get its first and last elements.
> 0 votes

# Answer
# Python, 35 34 bytes

```
lambda s:sorted(s+s[:1])[::len(s)]

```

Alternative version:

```
lambda s:sorted(s+s)[::len(s)*2-1]

```

Old version, 35 bytes.

```
lambda s:sorted(s+[s[0]])[::len(s)]

```

Fairly simple: take the input list, append the first element, sort it, then take the first and (length)th element of the resulting list. As the length of the input after appending an element is length + 1, this ends up taking the first and last element of said list, which are the minimum and maximum elements.
> 0 votes

# Answer
# Pyke, ~~5~~ 4 bytes

```
S'he

```

Try it here!

```
S    - sorted(input)
 'he - ^[0], ^[-1]

```
> 0 votes

# Answer
# dc, 45 bytes

```
[dsa]dsAx[dsz]dsZx[dla>Adlz<Zs.z0<f]dsfxlzlaf

```

This is a fairly straightforward equivalent of the C++ reference code:

```
#Test data
0 15 2 3 7 18 _2 9 6 _5 3 8 9 _14

# Uses two variables: a for min, and z for max

# Functions A and Z simply store a copy to a and z respectively.  Call
# them both, to initialize the variables.
[dsa]dsAx
[dsz]dsZx

# Function f is the main work - define and call it
[
    dla>A                       # copy into a if lower
    dlz<Z                       # copy into z if higher
    s.                          # discard value
    z0<f                        # recurse until end of input
]dsfx

# print the result
lzlaf

```
> 0 votes

# Answer
## C#, 60 bytes

```
n=>{System.Array.Sort(n);return new[]{n[0],n[n.Length-1]};};

```

A naïve method at 93 bytes:

```
n=>{var r=new[]{n[0],n[0]};foreach(int i in n){if(i<r[0])r[0]=i;if(i>r[1])r[1]=i;}return r;};

```
> 0 votes

# Answer
# Octave, 35 bytes

```
@(x)[x(all(t=x<=x')) x(sum(t)==1)]

```

This is an anoynymous function. Try it at ideone.

The code avoids using sorting. Namely, it does all pairwise "less than or equal" comparisons between elements of the input. The minimum is the element for which *all* comparisons are true. The maximum is that for which *only one* comparison is true.
> 0 votes

# Answer
# zsh, 22 bytes

```
(){echo $1 $_} ${(n)@}

```

defines a lambda function that prints its first arg (`$1`) and the last argument to the previous command (`$_`), and passes it `$@` after sorting it so the previous command becomes the invocation of that lambda

---

# zsh, 21 bytes

this only works fine if there's more than 1 argument :(

```
<<<"${${(n)@}/ * / }"

```

sorts `$@`, makes it a string and replaces everything from the first space to the last one with a single space, then passes it as input to cat with `<<<`

---

usage:

```
$ ./minmax 23 342 21 10
10 342

```
> 0 votes

# Answer
# Scala, 55 bytes

```
val s=args.map(_.toInt).sorted
print(s.head+" "+s.last)

```

To execute:

`$ scala minmax.scala 1 2 3 4 5 6 7 8 9`
> 0 votes

# Answer
# dc, 110 bytes

```
?ddsMsmzdsAsa[z1-:az0<S]dsSx[>R]s?[la;asM]sR[lM]sQ[lQxla1-dsa;al?xla0<N]dsNxlAsa[<R]s?[la;asm]sR[lm]sQlNxlmlMf

```

*Help me, `dc`ers! You are my only hope!*

Thanks to @seshoumara for finding that bug!

I'll add an explanation later. Here it is broken up a bit:

```
?dd sM sm
zd sA sa
[z 1- :a z0<S]dsSx
 [>R]s?
 [la;asM]sR
 [lM]sQ
[lQx la 1- dsa ;a l?x la0<N]dsNx
lA sa
 [<R]s?
 [la;a sm]sR
 [lm]sQ
lNx
lm lM f

```
> 0 votes

# Answer
## Bash + coreutils, 30 bytes

```
tr \  \\n|sort -n|sed '$p;1!d'

```

The sed script prints, after the input is sorted, the first and last integers.
> 0 votes

# Answer
# C++14, 66 bytes

As unnamed lambda returning via reference parameters. Accepts any random access container of integers.

```
[](int&a,int&b,auto&C){a=b=C[0];for(auto x:C)a=x<a?x:a,b=x>b?x:b;}

```

Ungolfed and usage:

```
#include<vector>
#include<iostream>

auto f=
[](int&a,int&b,auto&C){
  a=b=C[0];
  for(auto x:C)
    a=x<a?x:a,
    b=x>b?x:b;
}
;

int main(){
  std::vector<int> v{1,2,3,4,5,6,7,8,9,0,10,121,-12,100,100,100};
  int a;
  int b;
  f(a,b,v);
  std::cout << a << ", " << b << std::endl;
}

```
> 0 votes

# Answer
# Tcl, 62 bytes

```
puts [lindex [set L [lsort -r [join $argv]]] 0]\ [lindex $L e]

```

Try it online!
> 0 votes

# Answer
## Clojure, 28 bytes

```
#((juxt first last)(sort %))

```

At least juxt is mildly interesting.
> 0 votes

# Answer
## Python, 110 Bytes

Long, but it doesn't use sort.

```
def m(a):
 d=a[0]
 if len(a)==1:return d,d
 b,c=m(a[1:])
 if b>=d>=c:return b,c
 if d>b:return d,c
 return b,d

```

Output is a tuple of the form (max, min). Probably the least computationally efficient way to get the max/min of an array (other than bongo sorting it :P)
> 0 votes

# Answer
# Python, 97 bytes

```
def k(s):
 d=s[0]
 if s[1:]:
  a,b=k(s[1:])
  return(a+d+abs(a-d))/2,(b+d-abs(b-d))/2
 return d,d

```

Only clever part is that in python `[]` is falsy. Only builtin used is abs.

It uses more builtins than the 110 byte python solution, and more bytes than the 26 byte solution using sort.
> 0 votes

# Answer
# x86 opcode, 19 bytes

```
00: mov ebx, [esi]
02: mov edx, ebx
04: lodsd
05: cmp eax, ebx
07: cmovg ebx, eax
0A: cmp eax, edx
0C: cmovl edx, eax
0F: loop lp1
11: xchg eax, ebx
12: ret

```

Input: ECX(length), ESI(array)

Output: EAX(max), EDX(min)

Removing `xchg eax, ebx` makes 18B but output is not usual reg
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 87 bytes

```
	M =INPUT
	N =M
R	I =INPUT	:F(O)
	N =LT(I,N) I
	M =GT(I,M) I	:(R)
O	OUTPUT =N ' ' M
END

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `h`, 3 bytes

```
ṠḲZ

```

Try it online!

## Thunno 2, 4 bytes

```
Ṡçht

```

Try it online!

#### Explanation

```
ṠḲZ   # Implicit input
Ṡ     # Sort the list in ascending order
 Ḳ    # Bifurcate: duplicate and reverse
  Z   # Zip the two lists together
      # Implicit output of first item

```

```
Ṡçht  # Implicit input
Ṡ     # Sort the list
 ç    # Parallelly apply:
  h   #  First item
   t  #  Last item
      # Implicit output

```
> 0 votes

# Answer
# Swift, 77 bytes

```
let f={(($0+[]).reduce(Int.max){$1>$0 ?$0:$1},$0.reduce(.min){$1<$0 ?$0:$1})}

```

The relatively obvious approach. I believe this is how the `max()` and `min()` methods are actually implemented for `Sequence` in the standard library.
> 0 votes

# Answer
# Vyxal 3, 3 bytes

```
SÞh

```

Try it Online!

sort, take the ends
> 0 votes

# Answer
# J-uby, 20 bytes

```
:sort|-[:first,:pop]

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, number, array
---


title: No A, just CAPS LOCK

text:
# Question
Title: No A, just CAPS LOCK
What happens when the `CapsLock` key on your keyboard doesn't have a notch in it?

*"This hPPENS."*

The goal of this program is to consistently emulate keyboard misses where each `A` press is replaced with `CapsLock`. Uppercase 'A's from the source should yield the same effect. **When `CapsLock` is enabled, capitalization is reversed.**

# Test Cases

```
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."

"Compilation finished successfully."
-> "CompilTION FINISHED SUCCESSFULLY."

"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
-> "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"

"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."

"aAaaaaAaaaAAaAa"
-> "" (Without the notch, no one can hear you scream)

"CapsLock locks cAPSlOCK"
-> "CPSlOCK LOCKS CPSlOCK"

"wHAT IF cAPSlOCK IS ALREADY ON?"
-> "wHt if CPSlOCK IS lreDY ON?"

```

The winning criterion is, as usual, the size of the submitted program's source code.

# Answer
> 137 votes
# AutoHotKey, 7 bytes

```
a::vk14

```

// Is this valid? This really do what OP want -- replace `a` by `CapsLock (vk14)`.

Run this program, and type the input from keyboard..

# Answer
> 36 votes
# , 9 bytes

```
ò/ãa
xg~$

```

Try it online!

Hexdump:

```
00000000: f22f e361 0a78 677e 24                   ./.a.xg~$

```

Explanation:

```
ò       " Recursively:
 /ãa    "   Move forward to the next 'a' (upper or lowercase)
        "   This will break the loop when there are no more 'a's
x       "   Delete the 'a'
 g~$    "   Toggle the case of every character after the cursor's position.

```

# Answer
> 26 votes
# Vim, 16 bytes

```
qq/\ca
xg~$@qq@q

```

Assumes the input is on a single line

## Explanation

```
qq            Start a loop
 /\ca␊         Find the first occurence of an a, end the loop if there are none left
 xg~$          Remove it and invert the case of the rest of the file
@qq@q         End the loop

```

# Answer
> 16 votes
# C, 72 bytes

*Thanks to @Ton Hospel for helping to save 16 bytes!*

```
t,c;f(char*s){for(t=0;c=*s++;6305%c?putchar(isalpha(c)?c^t:c):(t^=32));}

```

Try it online!

# Answer
> 13 votes
# Husk, 11 bytes

```
Γ·§?m\:€"Aa

```

Try it online!

## Explanation

I'm using the somewhat obscure overloading of `Γ` called `listNF`, which constructs recursive functions that operate on lists. It corresponds to the following Haskell pattern:

```
listNF f = g
  where g (x : xs) = f g x xs
        g [] = []

```

The idea is that `listNF` takes a helper function `f` and returns a new function `g`, which takes a list. The function `f` takes a function, which will always be `g`, and the head `x` and tail `xs` of the list, and does something with them. In our application, `f` calls `g` recursively on `xs`. The program is interpreted like this:

```
Γ (· (§ (?m\) : (€"Aa")))
Γ (                     )  Create a function g that takes a list (x:xs) and applies a function on x and xs.
   · (                 )   Compose g with second argument of function in parentheses.
                           Instead of x and xs, the function is called on x and the result of a recursive call of g on xs.
                (€"Aa")    Check if x is 'A' or 'a'.
        (?m\)              If it is, then swap the case of every char in g(xs).
      §       :            Otherwise, prepend x to g(xs).

```

# Answer
> 12 votes
# Retina, ~~33~~ ~~21~~ 17 bytes

```
i(Tv`lL`Ll`a.*
a

```

**Try it online**

**Explanation:**

```
i(              i is for case-insensitive, the paren makes it modify both stages
  Tv`           Transliteration, with simple overlaps (v) - 1 match at every start pos
     lL`Ll`     Replace lowercase with uppercase, and vice versa
           a.*  Every 'a' will match, overlapping to the end of the string
                This swaps the case on all letters after each 'a'
a               Replace all 'a's with nothing

```

*-12 bytes thanks to Martin*
*-4 bytes thanks to Leo*

# Answer
> 7 votes
# JavaScript (ES6), ~~93~~ ~~88~~ ~~84~~ 82 bytes

*(saved 5 bytes thanks to @Shaggy, 4 bytes thanks to @user81655, and 2 bytes thanks to @l4m2.)*

```
a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())

```

**Test cases:**

```
let f=

a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())

console.log(f("The quick brown fox jumps over the lazy dog."));
console.log(f("Compilation finished successfully."));
console.log(f("What happens when the CapsLock key on your keyboard doesn't have a notch in it?"));
console.log(f("The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."));
console.log(f("aAaaaaAaaaAAaAa"));
console.log(f("CapsLock locks cAPSlOCK"));
console.log(f("wHAT IF cAPSlOCK IS ALREADY ON?"));
```

# Answer
> 7 votes
# , 92 bytes

```
cat(`[<-`(v<-el(strsplit(scan(,""),"a|A")),w<-c(F,T),chartr("a-zA-Z","A-Za-z",v)[w]),sep="")

```

Thank @Giuseppe for fixing the answer.

**Explanation**

```
# Write
cat(
  # Replace and return, this is the function that powers
  # the R store at index operations, a[i]<-b
  `[<-`(
    # First arg - what to replace = extract first list element
    # of a string input after splitting at a or A
    v<-el(strsplit(scan(,""),"a|A")),
    # Second arg - index to replace = abuse vector recycling
    # to create infinite F, T, F, T, F, etc series
    w<-c(F,T),
    # Third arg - replacement values = replace with case toggled letters
    chartr("a-zA-Z","A-Za-z",v)[w]),
  # Write without separation
  sep="")

```

Try it online!

# Answer
> 7 votes
# Java 8, ~~119~~ ~~108~~ 98 bytes

```
s->{int f=0,t;for(int c:s)if((t=c&95)==65)f^=1;else System.out.printf("%c",f<1|t<66|t>90?c:c^32);}

```

-11 bytes thanks to *@OlivierGrégoire*.
-10 bytes thanks to *@Nevay*.

**Explanation:**

Try it online.

```
s->{                           // Method with char-array parameter and no return-type
  int f=0,t;                   //  Flag-integer, starting at 0
  for(int c:s)                 //  Loop over the characters of the input as integers
    if((t=c&95)==65)           //   If the current character is an 'A' or 'a':
      f^=1;                    //    Toggle the flag (0→1 or 1→0)
    else                       //   Else:
      System.out.printf("%c",  //    Print integer as character
        f<1|                   //     If the flag-integer is 0,
        t<66|t>90?             //     or the current character isn't a letter:
         c                     //      Simply output the character as is
        :                      //     Else (the flag it 1 and it's a letter)
         c^32);}               //      Print it with its case reversed

```

# Answer
> 7 votes
# Python, 63 bytes

```
f=lambda s:s and[s[0]+f(s[1:]),f(s[1:]).swapcase()][s[0]in"aA"]

```

Another Python solution, works in Python 2 and 3. Takes a very long time for all but small inputs.

# Answer
> 6 votes
# Perl 5 `-p`, ~~31~~ ~~30~~ 29 bytes

-1 byte thanks to @nwellnhof

-1 byte thanks to @ikegami

```
#!/usr/bin/perl -p
s/a([^a]*)a?/$1^uc$1^lc$1/egi

```

Try it online!

# Answer
> 6 votes
# Ruby, ~~42~~ 41 bytes

```
->s{s.sub!(/a(.*)/i){$1.swapcase}?redo:s}

```

Try it online!

A lambda accepting a string, mutating the string in place, and returning it. The trick here is that `sub` returns the string (a truthy value) if a substitution was made, and returns `nil` otherwise. The existence of `swapcase` is pretty handy, too.

-1 byte: Replace boolean logic with ternary operator, thanks to Asone Tuhid

```
->s{
  s.sub!(/a(.*)/i){     # Replace "a" followed by anything with
    $1.swapcase         #   the case-swapped capture group
  } ? redo              # If a match was found, restart the block
    : s                 # Otherwise, return the modified string
}

```

# Answer
> 6 votes
# C, 167 168 158 131 bytes

Thanks for @Martin Ender for the code review: I've switched the stream processing for string processing to help with reusability. Also many thanks to @RiaD and @ceilingcat for their suggestions.

```
c,d;(*t[][2])()={{isupper,tolower},{islower,toupper}};f(char*s){for(d=1;c=*s++;)t[0][1](c)==97?d=!d:putchar(t[!t[d][0](c)][1](c));}

```

Try it online!

# How does it work?

```
/* int c is the input character,
   int d is the Caps Lock flag (1=off, 0=on)  starting as "Off". */
int c, d;
/* array of comparison functions and transformation functions for each state */
(*t[][2])() = {{isupper, tolower}, {islower, toupper}};

f(char *s) {
  /* Loop if we haven't hit the terminator */
  for(d = 1; c = *s++;)
    t[0][1](c) == 97 ?
      /* If tolower(c)=='a' then flip the Caps Lock state */
      d=!d:
      /* Otherwise, convert character according to the following table:

                       Character case
         Caps Lock  UPPER       LOWER
                ON  tolower()   toupper()
               OFF  toupper()   tolower()
      */
      putchar(t[!t[d][0](c)][1](c));
  }
}

```

# Notes

* `s[][]` is where the magic happens: `[][0]` is the comparison function and `[][1]` is the related transformation function for each state.
* `!` is applied to the comparison function to force it into the range \[0,1\].

# Answer
> 6 votes
# PowerShell Core, 105 bytes

```
"$args"|% t*y|%{if($_-in97,65){$c=!$c}else{Write-Host -n($_,("$_"|%("*per","*wer")[$_-in65..90]))[!!$c]}}

```

Try it online!

What with no real ternary operator and no default alias for printing to screen, it's not that short.

* `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `"$args".ToCharArray()`
* `Write-Host -n` is for the parameter `-NoNewLine`
* `"$_"` turns the `[char]` type back to `[string]` (chars have no upper/lower case in .Net)
* `|% *per` does the same method call shortcut as earlier, but for `.ToUpper()`, same with `.ToLower()`
* `($a,$b)[boolean test]` abused as fake-ternary operator
* `!!$c` force-casts to `[bool]` here it starts undefined `$null` so it gets forced it into existence as "caps lock: $false".

# Answer
> 5 votes
# Jelly, 14 bytes

```
Œu=”Aœp⁸ŒsJḤ$¦

```

Try it online!

Full program.

Explanation:

```
Œu=”Aœp⁸ŒsJḤ$¦ Arguments: x
Œu             Uppercase x
  =”A          ^ Equals 'A' (vectorizes)
     œp⁸       ^ Partition ⁸ [⁸=x]
             ¦ Apply link A, keep results at specific indices B
        Œs     A: Swap case
            $  B: Form a >=2-link monadic chain
          JḤ      Arguments: y
          J       Get list indices ([1, length(list)]) of y
           Ḥ      Double (vectorizes) ^
                  This way, we only "apply" link A to even indices, so every second
                  element, starting from the secondd one.

```

# Answer
> 5 votes
# 6502 machine code routine (C64), 51 bytes

```
A0 00 84 FE B1 FC F0 2A C9 41 F0 06 90 1A C9 C1 D0 08 A9 80 45 FE 85 FE B0 11
B0 06 C9 5B B0 08 90 04 C9 DB B0 02 45 FE 20 16 E7 C8 D0 D6 E6 FD D0 D2 60

```

Expects a pointer to a 0-terminated input string in `$fc/$fd`, outputs to the screen.

### Commented disassembly

```
 .caps:
A0 00       LDY #$00
84 FE       STY $FE             ; init capslock state
 .loop:
B1 FC       LDA ($FC),Y         ; next char from string
F0 2A       BEQ .done           ; NUL -> we're done
C9 41       CMP #$41            ; compare to 'a'
F0 06       BEQ .isa            ; if equal, toggle capslock
90 1A       BCC .out            ; if smaller, direct output
C9 C1       CMP #$C1            ; compare to 'A'
D0 08       BNE .ctog           ; if not equal, check for letter
 .isa:
A9 80       LDA #$80            ; toggle bit 7 in caps lock state
45 FE       EOR $FE
85 FE       STA $FE
B0 11       BCS .next           ; and go on
 .ctog:
B0 06       BCS .cZ             ; if char larger 'A', check for 'Z'
C9 5B       CMP #$5B            ; compare with 'z'+1
B0 08       BCS .out            ; larger or equal -> direct output
90 04       BCC .tog            ; smaller -> apply capslock
 .cZ:
C9 DB       CMP #$DB            ; compare with 'Z'+1
B0 02       BCS .out            ; larger or equal -> direct output
 .tog:
45 FE       EOR $FE             ; toggle bit from capslock state
 .out:
20 16 E7    JSR $E716           ; output char
 .next:
C8          INY                 ; and loop to next char
D0 D6       BNE .loop
E6 FD       INC $FD
D0 D2       BNE .loop
.done:
60          RTS

```

---

### Example assembler program using the routine:

**Online demo**

**Code in ca65 syntax:**

```
.import caps ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
string:         .res    $800

.data
prompt:         .byte   $d, "input> ", $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<string        ; read string into buffer
                sta     $fc
                lda     #>string
                sta     $fd
                jsr     readline

                lda     #>string        ; call our caps routine on buffer
                sta     $fd
                jmp     caps

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in $fc/$fd
; NO protection agains buffer overflows !!!
.proc readline
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
                lda     $fd
                sta     $2              ; initial page of string buffer
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $fb             ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     prepout         ; no -> to normal flow
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                bne     prepout         ; not zero -> ok
                lda     $2              ; otherwise check if we're in the
                cmp     $fd             ;    first page of the buffer
                beq     getkey          ; if yes, can't use backspace
prepout:        ldx     $cf             ; check cursor phase
                beq     output          ; invisible -> to output
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                cli                     ; enable interrupts
output:         lda     $fb             ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                cli                     ; enable interrupts
                lda     $fb             ; load character
store:          cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
                inc     $fd             ; otherwise advance buffer page
                bne     getkey
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                iny
                bne     termidxok       ; and advance ...
                inc     $fd
termidxok:      sta     ($fc),y         ; store terminator in buffer
                inc     $cc             ; disable cursor blinking
                rts                     ; return
backspace:      ldy     $fe             ; load buffer index
                bne     bsidxok         ; if zero
                dec     $fd             ;   decrement current page
bsidxok:        dey                     ; decrement buffer index
                sty     $fe
                bcs     getkey          ; and get next key
.endproc

```

# Answer
> 4 votes
# 05AB1E, 12 bytes

```
õ?„AaS¡Dvć?š

```

Try it online!

**Explanation**

```
õ?             # print an empty string (to account for the special case of only A's)
  „AaS¡        # split on occurrences of "A" or "a"
       D       # duplicate
        v      # for each element in the top copy
         ć?    # extract and print the head of the other copy
           š   # switch the case of the rest of the other copy

```

# Answer
> 4 votes
# PHP ~~101~~ 99 bytes

```
for($s=$argn;$i<strlen($s);$i++)lcfirst($s[$i])==a?$s=strtolower($s)^strtoupper($s)^$s:print$s[$i];

```

Run like this:

```
echo '[the input]' | php -nR '[the code]'

```

Ungolfed:

```
for ($s = $argn; $i < strlen($s); $i++) {
    if (lcfirst($s[$i]) == 'a') {
        $s = strtolower($s) ^ strtoupper($s) ^ $s; // Flip the whole string's case.
    } else {
        print $s[$i]; // Print the current letter.
    }
}

```

This just loops through the string with a for loop, and on each iteration it checks if the current letter is `a`, if so, then flip the case of the whole string (method from here), and if not, then print the current letter.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 70 bytes

```
#//.{x___,"a"|"A",y___}:>Join[{x},ToUpperCase@#+ToLowerCase@#-#&@{y}]&

```

Try it online!

Takes input and output as a list of characters. For convenience I've added code in the footer to convert this from and back to a string.

# How it works

The `#//.{x___,"a"|"A",y___}:>Join[{x},`...`{y}]&` part is standard: we find the first `A` (uppercase or lowercase), reverse case of that comes after the `A`, and repeat until there are no more `A`'s to be found.

The interesting part is how we reverse case: the function `ToUpperCase@# + ToLowerCase@# - #&`. We add together the upper-cased version of the input and the lower-cased version of the input, then subtract the actual input. For example, given the list `{"I","n","P","u","T"}` this computes

```
{"I","N","P","U","T"}+{"i","n","p","u","t"}-{"I","n","P","u","T"}

```

which threads over lists as

```
{"I"+"i"-"I","N"+"n"-"n","P"+"p"-"P","U"+"u"-"u","T"+"t"-"T"}

```

and although Mathematica doesn't have any particular way of adding two strings, it's smart enough to simplify `a+b-a` to `b` for any values of `a` and `b`, including string values, so this simplifies to `{"i","N","p","U","t"}`.

# Answer
> 4 votes
# Fortran (GFortran), 307 bytes

```
CHARACTER(999)F,G
G=' '
READ(*,'(A)')F
N=1
M=1
DO I=1,999
IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN
M=-M
ELSEIF(M==1)THEN
G(N:N)=F(I:I)
N=N+1
ELSE
J=IACHAR(F(I:I))
SELECTCASE(J)
CASE(65:90)
G(N:N)=ACHAR(J+32)
CASE(97:122)
G(N:N)=ACHAR(J-32)
CASE DEFAULT
G(N:N)=F(I:I)
ENDSELECT
N=N+1
ENDIF
ENDDO
PRINT*,TRIM(G)
END

```

Try it online!

Since Fortran has not "advanced" tools for dealing with strings, I came up with this little monster.

Indented and commented:

```
CHARACTER(999)F,G	!Define input and output strings (up to 999 characters)
G=' '			!Fill output with spaces
READ(*,'(A)')F		!Take input
N=1			!Represent the position to be written in output string
M=1			!M=-1: Change case; M=1: Do not change case
DO I=1,999
	IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN	!If the character is A...
		M=-M				!Ah-ha - you pressed cPS-LOCK!
	ELSEIF(M==1)THEN			!Case the character is not A, and do not need to change case...
		G(N:N)=F(I:I)			!...only copy the character
		N=N+1
	ELSE !Otherwise...
		J=IACHAR(F(I:I))			!...get ascii of current character
		SELECTCASE(J)
			CASE(65:90)			!If is upper case,
				G(N:N)=ACHAR(J+32)	!now is lower case
			CASE(97:122)			!If is lower case,
				G(N:N)=ACHAR(J-32)	!now is upper case
			CASE DEFAULT			!If do not belong to alphabet,
				G(N:N)=F(I:I)		!simply copy the character
		ENDSELECT
		N=N+1
	ENDIF
ENDDO
PRINT*,TRIM(G) !Trim out trailing spaces
END !That's all folks!

```

# Answer
> 4 votes
# MATL, ~~23~~ 20 bytes

```
'a A'Yb&Ybt2L)Yo2L(g

```

Try it online!

### Explanation:

```
'a A'Yb   % form a cell array containing {'a', 'A'}
&Yb       % split input into substrings, with either of those ('a' or 'A') as delimiters
t2L)      % extract out the even positioned cells from that result
Yo        % switch the case of those substrings
2L(       % place the result back in even positioned cells of the original cell array
g         % convert cell array to matrix, concatenating all substrings in the process
          % implicit output

```

---

Older answer (23 bytes):

"H@'aA'm?~XHx}@w~?Yo\]&h

Other methods I tried:

```
0w"@t'aA'm?x~}y?Yo]w]]xv!
t'aA'mXHYsot&y*XzcYowf([]H(
t'aA'mXHYsoy3Y2m*32*Z~c[]H(

```

# Answer
> 4 votes
# Julia 1.0, 82 bytes

```
s->foldl((b,c)->c∈"aA" ? !b : (print(c+32isletter(c)sign('_'-c)b);b),s,init=1<0)

```

## Explanation

### De-golfed:

```
function f(s::String)::Bool
    foldl(s, init=false) do b, c
        if c ∈ "aA"
            return !b
        else
            print(c + 32 * (isletter(c) & b) * sign('_'-c))
            return b
        end
    end
end

```

`foldl(f, s, init=false)`: takes a function `f` that maps a state and a `Char` `c` to a new state. Applys `f` repeatedly over each `Char` of the string `s`, always passing the state previously returned by `f` back to `f`. `init` is the initial state. Here the state represents whether caps-lock is on.

`if c in "aA"`: If `c` is an upper- or lowercase `'a'`, just return the opposite state.

`isletter(c) & b`: `Bool`, returns true iff `c` is a letter and `b` indicates, that caps-lock is on.

`sign('_'-c)`: `-1` if `c` is lowercase, `1` if `c` is uppercase.

`print(c + 32 * (isletter(c) & b) * sign('_'-c))`: `Bool`s act like 0/1 under simple arithmetic operations, so if caps-lock should have an effect, this either adds or substracts 32 from `c`, returning a `Char` with opposite case. Then just print that.

Try it online!

# Answer
> 4 votes
# Vyxal `s`, ~~<sup>12</sup>~~ ~~<sup>10</sup>~~ 9 bytes

*Saved 2 bytes by using  to split the string with a regex.*

*Saved 1 byte by using  to define the function.*

```
`a|A`ṡ⁽Nẇ

```

Try it Online!

Explanation:

```
           # Implicit input
`a|A`ṡ     # Split string every instance 'a' OR 'A'
      ⁽N   # Define a function that swaps the casing of strings
        ẇ  # Apply the function to every 2nd string
           # 's' flag: concatenate top of the stack and print

```

# Answer
> 3 votes
# SNOBOL4 (CSNOBOL4), ~~141~~ 92 bytes

```
	I =INPUT
S	I ANY("Aa") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S)
	OUTPUT =I
END

```

Try it online!

Assumes a single line of input.

A whopping 49 bytes saved by @ninjalj!

Line `S` does all the work, explained below:

```
I                    # in the subject string I match the following PATTERN:
 ANY("Aa")           # match A or a and
 REM . R             # match the remainder of I, assigning this to R
 =REPLACE(           # replace the PATTERN above with
          R, ...)    # R with swapped cases.
   :S(S)             # and if there was a match, goto S, else goto next line
```

# Answer
> 3 votes
# Haskell, 92 bytes

```
import Data.Char
g x|x<'['=toLower x|1>0=toUpper x
f(a:b)|elem a"aA"=f$g<$>b|1>0=a:f b
f x=x

```

Try it online!

## Explanation

First we declare `g` to be the function that maps lowercase to upper case and uppercase to lowercase. This is actually the majority of our bytecount. Then we define the function `f`. If the input to `f` is of the form `a:b` we do

```
f(a:b)
 |elem a"aA"=f$g<$>b
 |1>0=a:f b

```

`a` and `A` match the first pattern and thus we apply `f` to the input with it's case inverted. Otherwise we move `a` out front and apply `f` to `b`.

# Answer
> 3 votes
# Husk, 15 bytes

```
ω(F·+otm\↕·≠_'a

```

Try it online!

### Explanation

```
ω(F·+(tm\)↕·≠_'a) -- example input: "Bar, baz and Foo."
ω(              ) -- apply the following, until fixpoint is reached:
          ↕       -- | split string with predicate
           · _    -- | | the lower-cased character
            ≠ 'a  -- | | is not 'a'
                  -- | : ("B","ar, baz and Foo.")
  F               -- | apply the following to the tuple
    +             -- | | join the elements with..
   · (   )        -- | | ..the second element: "ar, baz and Foo."
       m\         -- | | | swap case: "AR, BAZ AND fOO."
      t           -- | | | tail: "R, BAZ AND fOO."
                  -- | : "BR, BAZ AND fOO."
                  -- : "BR, Bz ND fOO."

```

# Answer
> 3 votes
# Stax, 12 bytes

```
ìo'½`║â↨╪U?5

```

Run and debug it online

It splits on a regex, and then alternately toggles case. Here's the same program, unpacked, ungolfed, and commented.

```
"a|A"|s split on regex /a|A/
rE  reverse and explode array to stack
W   repeat forever...
p   print top of stack with no newline
:~p print top of stack, case inverted, with no newline

```

Run this one

# Answer
> 3 votes
# Japt v2.0a0, 16 bytes

```
e/a.*/i_År\l_c^H

```

Try it

---

## Explanation

```
e                   :Recursively replace
 /a.*/i             :RegEx /a.*/gi
       _            :Pass each match through a function
        Å           :  Slice off the first character
         r          :  Replace
          \l        :  RegEx /[A-Za-z]/g
            _       :  Pass each match though a function
             c^     :    Bitwise XOR the character code
               H    :    With 32

```

# Answer
> 3 votes
# Rust, 330 bytes

```
fn main(){let mut i=String::new();std::io::stdin().read_line(&mut i);let mut o=vec![];let mut c=false;for l in i.trim().as_bytes(){if*l==65||*l==97{c=!c;}else if c{if l.is_ascii_uppercase(){o.push((*l).to_ascii_lowercase());}else{o.push((*l).to_ascii_uppercase());}}else{o.push(*l);}}println!("{}",String::from_utf8(o).unwrap());}

```

Ungolfed

```
fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input);
    let mut output_chars = vec![];
    let mut capslock = false;
    for letter in input.trim().as_bytes() {
        if *letter == 65 || *letter == 97 {
            capslock = !capslock;
        } else if capslock {
            if letter.is_ascii_uppercase() {
                output_chars.push((*letter).to_ascii_lowercase());
            } else {
                output_chars.push((*letter).to_ascii_uppercase());
            }
        } else {
            output_chars.push(*letter);
        }
    }
    println!("{}", String::from_utf8(output_chars).unwrap());
}

```

Since this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'.

I'm new to Rust, so this might be golfable further.

# Answer
> 3 votes
## PHP 4, 77 76 75

```
foreach(spliti(a,$argn)as$b)echo$a++&1?strtoupper($b)^strtolower($b)^$b:$b;

```

Split into substrings by `A` (case insensitive) then toogle every second case.

Try it out here.

---

Old version

```
for(;a&$c=$argn[$i++];)trim($c,aA)?print($c^chr($f*ctype_alpha($c))):$f^=32;

```

walks over the string and toogles a flag if the current char is `a` or `A` else the char gets toogled depending on the flag and echoed.

# Answer
> 3 votes
## Javascript (ES6), ~~80~~ 79 bytes

*(Partly based off of this answer by Rick Hitchcock. Posting as a separate answer because I don't have sufficient reputation to comment.)*

*(Saved 1 byte thanks to @l4m2's post here.)*

```
a=>a.replace(j=/a()|./gi,(c,o=c[`to${j^c>{}?'Low':'Upp'}erCase`]())=>(j^=!o,o))

```

# Answer
> 2 votes
# Python 3, ~~78~~ 72 bytes

```
import re
lambda x:re.sub("[Aa](.*?)(a|A|$)",lambda m:m[1].swapcase(),x)

```

# Answer
> 2 votes
# \>\<\>, 139 129 bytes

```
1vo   <
>>i:"z")?^:"A"^>~~>~1$-
^o+< >::"aA"@=?^=?^$v
^o-^?  ("^"$*48:v?@:<
^ vv? )"Z":v?(< >>o
  >  ^v  < >:0 )?^;
  :< ^v?( "a"

```

A language with no concept of "characters" is surely the right tool for the job :)

# Answer
> 2 votes
# x86-64, 31 bytes

Conforms to the System-V calling convention, tested in Ubuntu 16.04. Takes input from a pointer to a null-terminated in rsi, and outputs the result as a null-terminated string in rdi. rdi is expected to pointer to a buffer that's already been allocated with sufficient size.

Disassembly for byte count:

```
   0:       31 d2                   xor    edx,edx
   2:       ac                      lods   al,BYTE PTR ds:[rsi]
   3:       88 c1                   mov    cl,al
   5:       24 df                   and    al,0xdf
   7:       3c 41                   cmp    al,0x41
   9:       75 05                   jne    10 <not_A>
   b:       80 f2 20                xor    dl,0x20
   e:       eb f2                   jmp    2 <loop>
  10:       2c 41                   sub    al,0x41
  12:       3c 19                   cmp    al,0x19
  14:       77 02                   ja     18 <not_ascii>
  16:       30 d1                   xor    cl,dl
  18:       91                      xchg   ecx,eax
  19:       aa                      stos   BYTE PTR es:[rdi],al
  1a:       84 c0                   test   al,al
  1c:       75 e4                   jne    2 <loop>
  1e:       c3                      ret

```

Commented Assembly (GAS):

```
.intel_syntax noprefix
.text
// rsi has the input char*, rdi has the output char*.
// Input char* is \0-terminated.
.global caps
caps:
    // Use this for xor mask.
    xor     edx, edx
// Loop is set up as a do-while loop.
loop:
    // al = *rdi++
    lodsb

    // Save the character we read into cl.
    // We use al because the instructions are shorter.
    mov     cl, al

    // Make upper case
    and     al, 0b11011111

    // 65 = 'A'
    cmp     al, 65
    jne     not_A
is_A:
    // Invert capitialization mask
    xor     dl,0x20
    // Continue
    jmp     loop

not_A:
    // Now we check if input character is ascii.
    // Basically, if (al-'A' > 'Z'-'A'), it's not ascii
    sub     al, 65
    cmp     al, 25

    ja      not_ascii
ascii:
    // Flip capitilization if necessary.
    xor     cl, dl

not_ascii:
    // Restore saved character that we read.
    // xchg is 1 byte, as opposed to mov, which is 2.
    xchg    ecx, eax

    // Write out the character to the output buffer.
    stosb

endloop:
    // If al == 0, break
    test    al, al
    jnz     loop

end:
    // Just return, we've already written out the null
    // character to the output string.
    ret

```

Testing code in C, takes the input string via the first command line argument, prints out the result string:

```
#include <stdio.h> //puts
#include <stdlib.h> //malloc, free
#include <string.h> //strlen

void caps(char* output, char* input);

int main(int argc, char** argv) {
    char* instr = argv[1];
    char* buf = malloc(strlen(instr) + 1);
    caps(buf, instr);

    // Print converted string.
    puts(buf);

    free(buf);
}

```

# Answer
> 2 votes
# Forth, 225 bytes

```
: d DUP ; : x SWAP ; : w WITHIN ; : a d d 65 = x 97 = OR ; : y d d 65 91 w x 97 123 w OR ; : ~ INVERT ; x VALUE s 0 VALUE f : l 0 DO I s + C@ a IF f ~ TO f THEN y IF f IF 32 XOR d THEN a ~ IF EMIT THEN ELSE EMIT THEN LOOP ; l

```

What happening:

```
: d DUP ;                     \ shortcut for duplicating value on stack
: a d d 'A' = SWAP 'a' = OR ;             \ testing, if char is 'a' or 'A'
: y d d 'A' '[' WITHIN SWAP 'a' '{' WITHIN OR ;   \ testing, if char is within letters
: ~ INVERT ;                      \ shortcut for negation
SWAP                          \ swap addr and len of the string after s" command
VALUE s                       \ pop addr to s
0 VALUE f                     \ write 0 to f(lag)
: l 0 DO                      \ declaration of loop named 'l' from 0 to len (len is laying on top of the stack, remember)
I s + C@                      \ push iteration number on stack and load char from s + iteration

        \ this IF is searching for 'a' or 'A'
a IF
    f ~ TO f              \ if we found 'a' or 'A', then flip the f(lag)
    THEN
y IF                      \ if char is letter
    f IF                  \ and f is set
    32 XOR d THEN             \ change case of symbol

    a ~ IF                \ if it's not 'a' or 'A' then print char
        EMIT
        THEN
ELSE
    EMIT                  \ print char
THEN
LOOP ;

l

```

---

Try it online!

Actually code in *tio* is **285 bytes**, but this is because *Footer* didn't work for defining string, so i had to include string definition in actual code.

# Answer
> 2 votes
# SM83, ~~29~~ 28 bytes; Z80, ~~30~~ 29 bytes

* SM83 version

```
06 00 2A 4F CB AF D6 41
28 0C FE 1A 79 30 01 A8
12 13 B7 20 ED C9 78 EE
20 47 18 E6

```
* Z80 version (changes in stars)

```
06 00 *7D 23* 4F CB AF D6 41
28 *0E* FE 1A 79 30 *03* A8
12 13 B7 20 *EE* C9 78 EE
20 47 18 *E7*

```

# Disassembly and explanation

```
fun:
    ld b,0      ; 06 00     we start out in non-swapping state
loop:
#ifdef SM83
    ld a,(hl+)  ; 2A        load character
#else
    ld a,(hl)   ; 7D
    inc hl      ; 23        Z80 doesn't have autoinc addressing
#endif
    ld c,a      ; 4F        save copy in c
    res 5,a     ; CB AF     Clear bit 5
    sub 65      ; D6 41     subtract 'A'
    jr z,is_a   ; 28 0C/0E  if 0, was 'A' or 'a'; handle that later
    cp 26       ; FE 1A     compare to 26
    ld a,c      ; 79        reload from copy
    jr nc,put   ; 30 01/03  skip next if was letter (<26)
    xor b       ; A8        xor in caps lock setting
put:
    ld (de),a   ; 12        store
    inc de      ; 13        and increment
    or a        ; B7        check if zero by self-or (cheap trick)
    jr nz,loop  ; 20 ED/EE  loop if wasn't 0
    ret         ; C9        and return otherwise
is_a:
    ld a,b      ; 78
    xor 32      ; EE 20
    ld b,a      ; 47        flip caps lock setting
    jr loop     ; 18 E6/E7  jump back to loop

```

Heavily based on corvus\_192's answer. The differences:

* I counted bytes of machine code, not assembly
* I changed `jp` (absolute jump, three bytes) to `jr` (relative jump, two bytes), saving five bytes
* I moved the case-fold (`res 5,a`) to before the test for A, saving a compare-to-constant and a jump (four more bytes saved)
* This produced the sequence `cp 65; jr z,is_a; sub 65`, which can be collapsed to `sub 65; jr z,is_a`, saving two more bytes.
* It's cheaper to test if `a` is 0 by executing `or a` (`and a` also works) than `cp 0`; it doesn't tell you sign, but we didn't need that.

In total, these changes (well, not the counting difference) save twelve bytes from the original.

# Answer
> 2 votes
# Swift, 110 bytes

```
import Darwin
var x=0,f={for c in($0+"").utf8{c&95==65 ?(x^=1,0).1:putchar(CInt(x>0&&66...90~=c&95 ?c^32:c))}}

```

`f(_:)` is the closure you want.

If you're on Linux instead of macOS, you can replace `import Darwin` with `import Glibc` to save a byte (and you have to do it anyway if you want it to compile). For platform independence, `import Foundation` can be used instead.

This is an almost direct port of @KevinCruijssen's Java answer to Swift, with:

* some things shuffled around,
* a call to `~=(lhs:rhs:)` (the pattern matching operator) to condense the range check,
* a tuple shenanigan to let us use the ternary conditional operator instead of `if`-`else`, and
* a bit of C interop abuse because Swift names are long.

## Notes

* `CInt` is a `typealias` for `Int32`, the type expected by `putchar(_:)` (for reasons beyond my mortal comprehension; C is weird).
* For reasons slightly closer to a realm I can grasp (i.e. exit codes), `putchar(_:)` also *returns* an `Int32`, meaning we can't directly put a call to it in a ternary conditional that expects `Void` (an alias for `()`), which is the result type of `x^=1` (because, in Swift, assignment operators rightfully don't return anything).

So, instead, I shoved `x^=1` into a tuple and added `0` as the second element, and then accessed it with `.1`. This still evaluates `x^=1`, but returns an `Int32` (the type the `0` literal is inferred as) rather than a `Void`, which calms down the type checker a bit.
* The `~=(lhs:rhs:)` operator is used internally for custom pattern matching (i.e. `switch` statements, `if case`, and the like). There's an overload defined on `ClosedRange` that checks if `rhs` is contained in `lhs`. We abuse that here.
* Because Swift really doesn't want you to do things like this with an ordinary `String`, we have to access the `utf8` property of the input to get a `[UInt8]` that we can iterate over.
* We need to concatenate `""` with `$0` (the implicit closure parameter, aka the input) to help the type checker figure out that `$0` is a `String`.

# Answer
> 1 votes
# Python 3, 114, 101, 97 bytes

```
import re
print(''.join(i.swapcase()if j%2else i for j,i in enumerate(re.split('a|A',input()))))

```

Split on all a's and toggle the case on the odd parts

Thanks @ElPedro !

# Answer
> 1 votes
# CJam, 31 bytes

```
q{_eu'A={;T!:T;}{_el_eu+|T=}?}%

```

**Explanation**

Loops through searching for a and non-a

Try it online!

---

# CJam, 47 bytes

Slightly more fun version

```
[q'a'Aer'A/_2%\2/z)\;{_[el_eu]z{\(@|1=\}%e_}%]z

```

Try it online!

**Explanation**

This code has two parts.

```
[
               Part 1
 q                          -> Read all input as a single string
 'a'Aer                     -> Replace 'a' in string with 'A'
 'A/                        -> Split by 'A' leaving empty sets
 _                          -> Duplicate
 2%                         -> Get all rows where i%2 is 0
 \                          -> Swap top two elements of stack
 2/                         -> Split into array with groups of length 2
 z                          -> Zip/Transpose
 )\;                        -> Right uncons, swap and pop.

               Part 2
 {
  _[el_eu]                  -> Create an array containing the lower case and upper case version
  z                         -> Zip/Transpose
  {
   \                        -> Swap top two
   (                        -> Uncons left
   @                        -> Rotate top three elements of stack
   |                        -> Set union
   1=                       -> Get element at array indice 1 (Wraps)
   \                        -> Swap top two
  }%                        -> Map onto every element of string
  e_                        -> Flatten
 }%                         -> Map onto every element of array
]z                          -> Zip/Transpose

```

The first part splits the string by 'A' leaving any empty sets behind. For the string "baacadE" that will give the following array.

```
["b", "", "c", "dE"]

```

That way, all normal case elements are at even indices and reverse case are odd. Which After executing the rest of the first part gives the following.

```
[["b", "c"], ["", "dE"]]

```

The second part will take the odd half and reverse the case of every string. This is done with the set union operator `|`. So for the element `"dE"` It will do the following. Since the set union operator preserves the order of the elements found in the first string/array we can always assume the reverse case element will be the second one in the string/array.

```
["dE", "dD"]
["dD", "dE"]
["dD", "E", "d"]
["E", "d", "dD"]
["E", "dD"]
["E", "D"]
...
["D", "E", "eE"]
["D", "Ee"]
["D", "e"]

```

All That is left to do is zip up the two halves.

# Answer
> 1 votes
# Chip, 64 bytes

```
,Ava
>B#
>C#.,Bb
>D##>Cc
>E##>Dd
`~+L^Ee
G~+)~vS
g,\-zm.
f{-F`~'

```

Try it online!

### How it works

*This is where I wish I could color-code the source. However, all of the below are full programs, and may be run on their own.*

First things first, write a (slightly mangled) cat program.

```
 A-a

     Bb
     Cc
     Dd
     Ee
G
g
f--F

```

Now invert capitalization of all characters `A-Za-z`.

This is determined by:

1. `c & 0x1F != 0`
    * Filter out anything whose low 5 bits are zero
    * This is done by the left most column and upper `~`
2. `((c & 0x1F) + 0x5) & ~0x1F == 0`
    * Filter out anything, that when added to 5, carries into or beyond the 6th bit
    * This is done by the two `#` columns
3. `c & 0x40 != 0`
    * Filter out anything that is less than 64
    * This is done by the lower `~`

The program assumes it will receive no characters above 127.

The results are aggregated and, the inversion is done by the `{` at the bottom.

```
,Ava
>B#
>C#. Bb
>D## Cc
>E## Dd
`~+' Ee
G~<
g,\*
f{-F

```

But attach that to a toggle (T flip-flop) that is initially off. Now, the toggle decides whether to invert the capitalization, and the filter from above decides which characters to apply it to. Put a `*` above the `m` to toggle on every cycle.

```
,Ava
>B#
>C#. Bb
>D## Cc
>E## Dd
`~+' Ee
G~<
g,\-zm.
f{-F`~'

```

Toggle the toggle when we see an `Aa`, and suppress that character too. We have an `Aa` if the filter above says we have `A-Za-z`, and the low five bits equal one (`c & 0x1F == 1`).

```
,Ava
>B#
>C#.,Bb
>D##>Cc
>E##>Dd
`~+L^Ee
G~+)~vS
g,\-zm.
f{-F`~'

```

# Answer
> 1 votes
# Python 3, 100 bytes

```
def f(x):x=x.replace('A','a').split('a');return''.join(i.swapcase()if i in x[1::2]else i for i in x)

```

Try it online!

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

```
u;f(char*s){for(u=0;*s;s++)u^=6305%*s?!putchar(*s&64?*s^u:*s):32;}

```

Similar to another solution but doesn't use `ctype` functions.

*-1 byte thanks to \[ceilingcat\]!*

Try it online!

# Answer
> 1 votes
# Clojure, 256 bytes

## Golfed

`(require[clojure.string :refer :all])(def u upper-case)(defn f[x](if(=(u x)x)(lower-case x)(u x)))(defn i[a](="A"(u a)))(defn g[x](let[v(vec(map str x))](join""(filter(complement i)(reduce-kv(fn[c k e](if(i e)(concat(take k c)(map f(drop k c)))c))v v)))))`

## Ungolfed

```
(ns acapslock.core
  (:require [clojure.string :as str]))

(defn flip
  [x]
  (if (= (str/upper-case x) x) (str/lower-case x) (str/upper-case x)))

(defn isa
  [a]
  (or (= "a" a) (= "A" a)))

(defn foo
  [x]
  (str/join "" (filter (complement isa) (reduce-kv (fn [coll idx elem] (if (isa elem)(concat (take idx coll) (map flip (drop idx coll))) coll)) (vec (map str x)) (vec (map str x))))))

```

## Explanation

The solution works in two steps:

* First, we go through the input character by character. If we find an `a` or an `A`, we flip the case of the rest of the string.
* Then we filter out all `a`'s and `A`'s.

## Tests

```
(ns acapslock.core-test
  (:require [clojure.test :refer :all]
            [acapslock.core :refer :all]))

(deftest a-test
  (testing "test cases"
    (is (= "" (foo "")))
    (is (= "The quick brown fox jumps over the lZY DOG." (foo "The quick brown fox jumps over the lazy dog.")))
    (is (= "CompilTION FINISHED SUCCESSFULLY." (foo "Compilation finished successfully.")))
    (is (= "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?" (foo "What happens when the CapsLock key on your keyboard doesn't have a notch in it?")))
    (is (= "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." (foo "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness.")))
    (is (= "" (foo "aAaaaaAaaaAAaAa")))
    (is (= "CPSlOCK LOCKS CPSlOCK" (foo "CapsLock locks cAPSlOCK")))
    (is (= "wHt if CPSlOCK IS lreDY ON?" (foo "wHAT IF cAPSlOCK IS ALREADY ON?")))

    ))

```

# Answer
> 1 votes
# 05AB1E (legacy), 11 bytes

```
„AaS¡εNFš]J

```

Try it online!

# Answer
> 1 votes
# Julia, 107 bytes

```
let b=false;[c in"aA" ? b=!b : print(b&&isletter(c) ? c<'@' ? c+32 : c-32 : c) for c::Char=read(stdin)];end

```

Try it online!

The `let` block is unfortunate, but apperently julia's scope is broken and b is undefined otherwise.

Here's the same program but with loops instead of comprehension, and `if` instead of conditionals.

```
 let b=false # whether to invert charachters
# normally this would be "for c in read(stdin,String)",
# but reading a byte array and converting the bytes to chars saves one (byte).
for c::Char in read(stdin)
if c in "aA"
   b = !b
else
   print(if b && isletter(c)
            if c<'@' # capitalization check
               c+32  # ascii code shenanigans to change case
            else
               c-32
            end
         else
            c # c is not a letter or we aren't swapping
         end)
end
end
end

```

# Answer
> 1 votes
# Julia 1.0, <sup>~~73~~</sup> 71 bytes

```
f(s,b=0)=[c∈"aA" ? b=32-b : print(c+isletter(c)sign('_'-c)b) for c=s]

```

Try it online!

Stolen and improved from Simeon Schaub's great answer

-2 bytes thanks to Czylabson Asa

# Answer
> 0 votes
# Pyth, 21 bytes

```
ssm+Pdr2edcscR\AcQ\a2

```

Try it here

### Explanation

```
ssm+Pdr2edcscR\AcQ\a2
           scR\AcQ\a   Split the input on 'a' and 'A'
          c         2  Split the blocks into pairs.
  m  d   d             For each pair...
   +P r2e              ... cAPSlOCK the second block.
ss                     Join the blocks together.

```

# Answer
> 0 votes
# Pyth, 19 bytes

```
s.e?%k2rb2b:Q"a|A"3

```

Try it here.

Saved one byte thanks to mnemonic.

# Answer
> 0 votes
# Charcoal, 21 bytes

```
ＦＳ¿⁼a↧ι≦¬κ¿κι¿№αι↧ι↥ι

```

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

```
ＦＳ

```

Loop through each character in the line of input.

```
¿⁼a↧ι

```

Test whether it equals `a` in lower case.

```
≦¬κ

```

If so then logically negate `k`. (Note that for some reason Charcoal considers `k`'s default value `None` to be truthy.)

```
¿κ

```

Otherwise check whether `k` is currently truthy.

```
ι

```

If so then just print the character.

```
¿№αι

```

Otherwise check whether the current character is an upper case letter.

```
↧ι

```

If it is then print it in lower case.

```
↥ι

```

Otherwise print it in upper case.

# Answer
> 0 votes
# Python 2, 103, 97 bytes

```
import re
def f(s):print"".join(j.swapcase()if i%2else j for i,j in enumerate(re.split('a|A',s)))

```

# Answer
> 0 votes
# APL (Dyalog Classic), ~~46~~ ~~41~~ 40 bytes

```
'aA'~⍨⊢819⌶⍨¨2|(⊢≠819⌶¨)+≠\∘(∨⌿'aA'∘.=⊢)

```

Try it online!

## How??

* `'aA'~⍨` \- Remove all `a`'s from ...
* `⊢819⌶⍨¨2|(⊢≠819⌶¨)` \- ... the alternating upper-and-lower-case of the argument ...
* `+≠\∘` ... based upon ...
* `(∨⌿'aA'∘.=⊢)` ... the position of `a` and/or `A`.

# Answer
> 0 votes
# Yabasic, 121 bytes

An anonymous function that takes input as a line of text from STDIN and outputs to STDOUT.

```
Line Input""s$
For i=1To Len(s$)
c$=Mid$(s$,i,1)
u$=Upper$(c$)
If u$="A"Then
d=!d
ElsIf d Then?u$;Else?Lower$(c$);Fi
Next

```

Try it online!

# Answer
> 0 votes
# Excel VBA, 115 bytes

A declared `sub`routine that takes input, `s` of expected type `variant/string` and outputs to the range `[A1]`.

```
Sub f(s)
For i=1To Len(s)
c=Mid(s,i,1)
u=UCase(c)
If u="A"Then d=Not d Else[A1]=[A1]+IIf(d,u,LCase(c))
Next
End Sub

```

# Answer
> 0 votes
# pwsh, 109 bytes

```
$Input|%{$i=$_[0]-ceq'a';$r='';foreach($s in $_.split('a')){$r+=($s.ToUpper(),$s.ToLower())[$i];$i=!$i};$r}

```

# Answer
> 0 votes
## Haskell, ~~199~~ 133 bytes

```
import Data.Char
l c|isUpper c=toLower c|1<2=toUpper c
f _""=""
f b(c:cs)|toLower c=='a'=f(not b)cs|1<2=(if b then l else id)c:f b cs

```

Run using `f False "<string>"`

Ungolfed version:

```
import Data.Char

flipCase c
    | isUpper c = toLower c
    | otherwise = toUpper c

f "" _ = ""
f b (c:cs)
    | toLower c == 'a' = f cs $ not b
    | True = (if b then flipCase else id) c:f b cs

```

# Answer
> 0 votes
# Haskell, ~~96~~ 94 Bytes

(Unix Line Endings)

```
import Data.Char
t=toUpper
i c|c>'Z'=t c|0<1=toLower c
f(x:s)|t x=='A'=f$i<$>s|0<1=x:f s
f x=x

```

# Answer
> 0 votes
# Pip, 22 bytes

(The `SC` operator was added because of this challenge.)

```
{LCaQ'a?xX!:ii?SCaa}Mq

```

Try it online!

### Explanation

```
                        i is 0, x is empty string (implicit)
                     q  Read a line of input
{                  }M   Map this function to its characters:
 LCa                     The character, lowercased
    Q'a                  Is it equal to lowercase a?
       ?                 If so:
          !:i             Logically negate i in place (0 -> 1, 1 -> 0)
        xX                Repeat the empty string that many times (thus, always return
                          empty string when the character is a/A)
                         Else:
             i?           Is i truthy (1)? If so, caps lock is on, so return:
               SCa         The character, swap-cased
                          Else return:
                  a        The character, unchanged

```

# Answer
> 0 votes
# K4, 49 bytes

**Solution:**

```
{@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}

```

**Examples:**

```
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"The quick brown fox jumps over the lazy dog."
"The quick brown fox jumps over the lZY DOG."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"Compilation finished successfully."
"CompilTION FINISHED SUCCESSFULLY."
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
"WhT Hppens when the CPSLOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"
q)k){@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"}"aAaaaaAaaaAAaAa"
""

```

**Explanation:**

Fairly heavy, will look at other answers to see if I can golf this down:

```
{@[x;&.q.mod[;2]@&-':w;.q.upper]_/|w:&"a"=_x,"a"} / the solution
{                                               } / lambda with implicit input x
                                           x,"a"  / append "a" to input
                                          _       / lowercase
                                      "a"=        / boolean list where input is "a"
                                     &            / indices where true
                                   w:             / save as w
                                  |               / reverse
                                _/                / drop over (remove these indices from...)
 @[ ;                 ;        ]                  / apply [var;indices;function]
                       .q.upper                   / uppercase
                  -':w                            / deltas of w
                 &                                / where, builds list of ascending values
                @                                 / apply
      .q.mod[;2]                                  / mod 2 to generate boolean list
   x                                              / apply uppercase to input x at these locations

```

**Notes:**

Think I may have missed the point. I enabled/disable caps when an `a` is encountered. Passes the first test cases but not the ones where caps is apparently already enabled...

# Answer
> 0 votes
# Lua, ~~152~~ 151 bytes

```
p=io.read()a=0s=""for c in p:gmatch"."do l=c:lower()if c:find"[aA]"then a=(a+1)%2 else s=s..((c:find"%A"or a==0)and c or l==c and c:upper()or l)end end

```

Try it online!

---

### Explanation

```
p = io.read() -- reads the input
a = 0
s = ""
for c in p:gmatch"." do -- loops through the string 'p' (the input) calling each character 'c'
  l = c:lower() -- stores the lowercase version of 'c'
  if c:find("[aA]") then -- if 'c' is a lowercase or uppercase 'A'
    a = (a+1)%2 -- flip the value of 'a' between 0 and 1, from what I've seen it uses less space
  else
    s = s..((c:find("%A") or a==0) and c or l==c and c:upper() or l)
    s = s..   -- append to the string 's'
            (c:find("%A") or a==0)   -- if this is not a letter or the "reversion" is off
                                   and c or   -- then append 'c' else
                                            l==c and c:upper() or l   -- if 'c' is lowercase then append it as uppercase else append it as lowercase
  end
end

```

If you have any questions, feel free to ask and i'll try to answer.

# Answer
> 0 votes
# **Lua 5.3, 137 bytes**

```
a=0s=""io.read():gsub(".",function(c)if c:find"[aA]"then a=not a else l=c:lower()s=s..(a and c or l==c and c:upper()or l)end end)print(s)

```

Try it online!

---

### Notes:

My result was very similar to @Visckmart above. But I included the `print(s)` in my byte count. Also the try it online test uses Lua 5.1, where my final result is in Lua 5.3. To make my final answer run on the website linked above I had to add a single space in between defining `a` and `s`: `a=0 s=""` which make it 138 bytes when using Lua 5.1

# Answer
> 0 votes
# Python 3, 110 bytes

```
code_golf=lambda s:"".join([j.swapcase()if i&1else j for i,j in  enumerate(__import__('re').split(r"a|A",s))])

```

# Answer
> 0 votes
# Gameboy Z80 Assembly, 186 bytes

```
f:
 ld b,0
l:
 ld a,[hli]
 ld c,a
 cp 65
 jp z,a
 cp 97
 jp z,a
 res 5,a
 sub 65
 cp 25
 ld a,c
 jp nc,o
 xor b
o:
 ld [de],a
 inc de
 cp 0
 jp nz,l
 ret
a:
 ld a,b
 xor 32
 ld b,a
 jp l

```

This answer was heavily influenced by Ian Chew's x86 assembly answer.

## Commented version

```
; input in hl
; output in de
; b is used for the caps lock state, 00000000 = no capslock, 00100000 = capslock
; a and c are used for the character
f:
 ld b,0
loop:
; load a character from the input and advance the source pointer
 ld a,[hli]
;save character in c
 ld c,a
; check if character is 'a' or 'A'
 cp 65
 jp z,is_a
 cp 97
 jp z,is_a
; check if character is a letter by setting the 5th bit to zero and checking for the range 25..65
 res 5,a
 sub 65
 cp 25
; load the character back from c
 ld a,c
; if it is not a letter, simply output it
 jp nc,output
; if it is a letter, apply the current case swap
 xor b
; output the character and advance the destination pointer
output:
 ld [de],a
 inc de
; end of input?
 cp 0
 jp nz,loop
; return
 ret

is_a:
; change the case swap mask by xoring with 32
 ld a,b
 xor 32
 ld b,a
; continue the loop
 jp loop

```

# Answer
> 0 votes
# MMIX, 60 bytes (15 instrs)

```
E3020000 83030000 E7000001
CBFF0320 25FFFF41 5AFF0003
C7020220 F1FFFFFA 33FFFF1A
48FF0002 C6030302 A3030100
E7010001 5B03FFF4 F8000000

```

# Disassembly and explanation:

```
fun SETL  $2,0              // E3020000: mask = 0
0H  LDBU  $3,$0,0           // 83030000: loop: chr = *src (src, dst are both char *)
    INCL  $0,1              // E7000001: src++
    ANDN  $255,$3,32        // CBFF0320: tmp = chr & ~32
    SUB   $255,$255,'A'     // 25FFFF41: tmp -= 'A'
    PBNZ  $255,1F           // 5AFF0003: iflikely(!tmp) goto nota
    XOR   $2,$2,32          // C7020220: mask ^= 32
    JMP   0B                // F1FFFFFA: goto loop
1H  CMPU  $255,$255,26      // 33FFFF1A: nota: tmp = tmp <=> 26
    BNN   $255,1F           // 48FF0002: if(tmp > 0) goto notlet
    XOR   $3,$3,$2          // C6030302: chr ^= mask
1H  STBU  $3,$1,0           // A3030100: notlet: *dst = chr
    INCL  $1,1              // E7010001: dst++
    PBNZ  $3,0B             // 5B03FFF4: iflikely(chr) goto loop
    POP   0,0               // F8000000: return

```

This was heavily inspired by corvus\_192's answer.

It's essentially the same algorithm, except with multiple simplifications due to MMIX's symmetric register architecture.

# Answer
> 0 votes
# Zsh, 97 ~~107~~ bytes

```
for c (${(s..)1})case $c {a|A)((j^=1));;[b-z])((j))&&c=$c:u;|[B-Z])((j))&&c=$c:l;|*)s+=$c;}
<<<$s

```

-10 thanks to @GammaFunction. Try it Online! ~~<sub>107bytes</sub>~~

# Answer
> 0 votes
# Uiua, ~~18~~ 17 bytes

```
/◇⊂⍜▽¯◿2⊛.⊜□≠@A⌵.

```

Try it

```
/◇⊂⍜▽¯◿2⊛.⊜□≠@A⌵.
               ⌵.  # Push an uppercase copy
            ≠@A    # Mask of those not equal to A
          ⊜□       # Partition, boxing each string
        ⊛.         # Copy, push the range 0 to its length
      ◿2           # Modulo 2 (alternating 0s and 1s)
   ⍜▽¯             # At positions with 1s, swapcase
/◇⊂                # Reduce by joining each unboxed string

```

Created with the help of Luminespire.

I don't like formatting Uiua explanations like this since it's hard to explain everything on one line (especially because I like to do pretty in-depth explanations). Particularly for Uiua it can feel awkward reading the code down and to the left while reading the explanation all the way to the right. But, there's a clear tradeoff, doing explanations this way takes much less time, and I don't have that much time right now so this'll do.

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


title: Reconstruct a list from its prefixes

text:
# Question
Title: Reconstruct a list from its prefixes
A list \\$\[a\_1,a\_2,a\_3 \cdots a\_n\]\\$ can be uniquely represented as an unordered list of its prefixes - \\$ \[\[a\_1\],\[a\_1, a\_2\], \[a\_1,a\_2,a\_3\] \cdots \[a\_1,a\_2,a\_3 \cdots a\_n\]\] \\$. This can be in any order - for example, \\$\[1, 2, 3\]\\$ could be represented by any of \\$\[\[1\],\[1,2\],\[1,2,3\]\]\\$, \\$\[\[3,2,1\],\[2,1\],\[1\]\]\\$, or \\$\[\[2, 1\], \[1\],\[3,1,2\]\]\\$; and these are all equivalent up to order and all represent \\$\[1, 2, 3\]\\$.

Your challenge is, given a (non-empty) list of the prefixes of a list of positive integers in any order, to return the list represented by that. The list may contain repeated items. This is , shortest wins!

## Testcases

Note: the order of the output does matter, e.g. for the third test case you must output `[6, 4, 8, 7]`, not `[7, 4, 8, 6]`.

```
[[1], [1, 2], [1, 2, 3]] -> [1, 2, 3]
[[2, 1], [1], [3, 1, 2]] -> [1, 2, 3]
[[6, 4, 8], [7, 4, 8, 6], [6, 4], [6]] -> [6, 4, 8, 7]
[[6, 2, 3, 1], [1, 2], [1], [6, 1, 2], [2, 2, 3, 1, 6]] -> [1, 2, 6, 3, 2]
[[2], [30, 2, 27, 40], [27, 40, 2, 89, 30], [2, 30, 27], [27, 2]] -> [2, 27, 30, 40, 89]
[[8, 4], [4, 8, 8, 4], [4, 4, 8], [4]] -> [4, 8, 4, 8]
[[22, 98, 62, 80], [80, 98], [22, 98, 10, 62, 80, 87, 2], [98], [62, 80, 98], [22, 98, 2, 62, 80], [2, 22, 98, 62, 87, 80]] -> [98, 80, 62, 22, 2, 87, 10]
[[43, 84, 56, 19], [56, 43], [43, 56, 19], [43]] -> [43, 56, 19, 84]

```

# Answer
> 28 votes
# Python 3, 51 bytes

```
lambda l,p=0:[-p+(p:=x)for x in sorted(map(sum,l))]

```

Try it online!

Take the sums of the input lists, sort them in increasing order, take adjacent differences. This works because the difference between the sums of two consecutive prefixes is just the added element, and sorting works because the numbers are positive.

# Answer
> 8 votes
# Jelly, 4 bytes

```
§ṢŻI

```

A monadic Link that accepts a list of lists of positive integers and yields a list of positive integers.

**Try it online!**

### How?

```
§ṢŻI - Link: Prefixes
§    - sums
 Ṣ   - sort
  Ż  - prefix a zero
   I - forward differences

```

# Answer
> 5 votes
# Haskell, 49 bytes

```
import Data.List
(zipWith(-)<*>(0:)).sort.map sum

```

Try it online!

You guessed it, another port of xnor's Python answer.

## Slightly different approach, ~~62~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes

*Another one bytes the dust thanks to Wheat Wizard.*

```
import Data.List
concat.(zipWith(\\)<*>([]:)).sortOn sum

```

Try it online!

Figured I'd try something different for the sake of variety. Concatenate the forward differences of the prefixes (plus the empty list) sorted by sum. Ties the first approach if the output can be a list of singletons.

# Answer
> 4 votes
# , 34 bytes

```
\(L)diff(c(0,sort(sapply(L,sum))))

```

Attempt This Online!

Uses the same approach as @xnor's answer.

# Answer
> 3 votes
# Python 2, 73 bytes

```
lambda L:reduce(lambda v,l:map(l.remove,v)and v+[l[0]],sorted(L,key=len))

```

Try it online!

An anonymous function that accepts a `L`ist of lists and returns a list as result.

**How does it work?**

With the input sorted by length (so `[[2, 1], [1], [3, 1, 2]]` becomes `[[1], [2, 1], [3, 1, 2]]`), for each sub`l`ist, remove the first occurrence of elements already `v`isited from `l` and mark the remaining element as `v`isited.

It works for duplicates.

# Answer
> 3 votes
# Haskell, ~~78~~ ~~71~~ 59 bytes

*-7 bytes thanks to @Wheat Wizard*, *-12 bytes thanks to @xnor*

```
f w|h:_<-[x|[x]<-w]=h:f[a++b|(a,_:b)<-span(/=h)<$>w]
f _=[]

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
¯ªéO¥

```

Try it online or verify all test cases.

**Explanation:**

```
¯ª     # Append an empty list to the (implicit) input list of lists
  é    # Sort these lists by length
   O   # Sum each inner list
    ¥  # Pop and get their forward differences
       # (after which this list is output implicitly as result)

```

# Answer
> 3 votes
# K (ngn/k), 11 bytes

```
-':.1<:\+/'

```

Try it online!

Another port of xnor's answer. `+/'` sums, `.1<:\` sort, `-':` differences.

# Answer
> 3 votes
# Haskell \+ hgl, 14 bytes

```
δ<(0:)<sm<<sj

```

Attempt This Online!

A simple shameless port of the haskell answer.

# Reflection

I'm a little bothered by the fact the empty prefix is not included in the input. Both because I am a helpless pedant and because it adds a bunch of bytes to my answer. It adds *5-bytes*, over a third of the total answer.

But the challenge is what it is, and I should expect challenges to do things that don't fit with my desire for recursive symmetry. The fact that this is such a deficit is indicative more that hgl needs to be more flexible.

* I need to change the type of `K`. It is virtually impossible for Haskell to ever infer its type, and so I have a 1-byte function which I consistently can't use for its intended purpose. This goes for helpers like `K0` and `Qi` as well.
* `paf` appears to consistently be more useful than `pa`, even though `pa` is given the 2-byte name. They should probably be swapped.
* I should add a version of `paf` which takes a "starting value". It would be helpful here. This can be implemented on `Scan` instead of foldable.
* A sort combined with a map would be good. Like `sB` but which returns the converted values instead of the pre-converted values.

# Answer
> 2 votes
# Uiua SBCS, 9 bytes

```
°\+⊏⍏.⍚/+

```

Try it!

Port of xnor's Python answer.

```
°\+⊏⍏.⍚/+
      ⍚/+  # sums
   ⊏⍏.     # sort
°\+        # differences

```

# Answer
> 2 votes
# MathGolf, 6 bytes

```
mΣs0▌│

```

Try it online.

**Explanation:**

```
m       # Map over each inner list of the (implicit) input-list of lists:
 Σ      #  Sum each inner list
  s     # Sort the sums from lowest to highest
   0▌   # Prepend a 0 to the list of sums
     │  # Pop and get the forward differences of this list
        # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# JavaScript (V8), 82 bytes

```
s=>(x=s.map(y=>y.reduce((a,c)=>a+c)).sort((a,b)=>a-b))&&x.map((z,i)=>i?z-x[i-1]:z)

```

Try it online!

Arnauld's magic, **66 bytes**

```
a=>a.map(b=>eval(b.join`+`)).sort((a,b)=>a-b).map(v=>-p+(p=v),p=0)

```

Try it online!

# Answer
> 1 votes
# Charcoal, 20 bytes

```
ＷΦθ⁼Ｌκ⊕Ｌυ⊞υ⁻Σ⊟ι↨υ¹Ｉυ

```

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

```
ＷΦθ⁼Ｌκ⊕Ｌυ

```

While there is a prefix with one more member than the number of terms collected so far, ...

```
⊞υ⁻Σ⊟ι↨υ¹

```

... subtract the sum of that prefix from the sum of the terms collected so far and push that to the (predefined empty) list of terms so far.

```
Ｉυ

```

Output the final list.

# Answer
> 1 votes
# APL+WIN, 19 bytes

Prompts for prefixes as nested vectors.

```
-2-/0,+/¨m[⍋+/¨m←⎕]

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# Scala 3, 84 bytes

Golfed version. Attempt This Online!

```
x=>{x.map(_.sum).sorted.foldLeft((Seq[Int](),0)){(A,c)=>val(a,p)=A;(a:+(c-p),c)}._1}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val inputs = List(
      List(List(1), List(1, 2), List(1, 2, 3)),
      List(List(2, 1), List(1), List(3, 1, 2)),
      List(List(6, 4, 8), List(7, 4, 8, 6), List(6, 4), List(6)),
      List(List(6, 2, 3, 1), List(1, 2), List(1), List(6, 1, 2), List(2, 2, 3, 1, 6)),
      List(List(2), List(30, 2, 27, 40), List(27, 40, 2, 89, 30), List(2, 30, 27), List(27, 2)),
      List(List(8, 4), List(4, 8, 8, 4), List(4, 4, 8), List(4)),
      List(List(22, 98, 62, 80), List(80, 98), List(22, 98, 10, 62, 80, 87, 2), List(98), List(62, 80, 98), List(22, 98, 2, 62, 80), List(2, 22, 98, 62, 87, 80)),
      List(List(43, 84, 56, 19), List(56, 43), List(43, 56, 19), List(43))
    )

    inputs.foreach { input =>
      val result = calculateDifference(input)
      println(s"Result: $result")
    }
  }

  def calculateDifference(lists: List[List[Int]]): List[Int] = {
    val sortedSums = lists.map(_.sum).sorted
    sortedSums.foldLeft((List[Int](), 0)) { (accAndPrev, curr) =>
      val (acc, prev) = accAndPrev
      (acc :+ (curr - prev), curr)
    }._1
  }
}

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=sum`, 46 bytes

```
sub{map{$c-=($t=$c+sum@$_);$t}sort{@$a-@$b}@_}

```

Try it online!

# Answer
> 1 votes
# jq, 71 bytes

```
sort_by(length)|while(any;.[0][0]as$i|map(del(.[index($i)]))[1:])[0][0]

```

Try it online!

We take the shortest prefix (which has a length of 1), remove it and remove its first (only) value from all remaining prefixes. This gives us a prefix list for the list's tail. We then repeat the process for that prefix list. This eventually gives us a prefix list for the target list and all its suffixes. We then take the first (only) value from the first (shortest) prefix in each of those lists, to get the elements of the target list in order.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 77 bytes

```
Fold[({x,y}={##};First@Select[Permutations@y,Most@#==x&])&,SortBy[#,Length]]&

```

Since it is difficult to improve Arnauld’s algorithm, I try to solve a more general problem.
This code reconstructs any list: with negative numbers, strings etc.

Try it online!

---
Tags: code-golf, array, set-theory
---


# Question
Title: Egyptian fraction representations of 1 without prime denominators
## Background

As noted in this question, for all positive integers \\$n\>2\\$ there exists at least one Egyptian fraction representation (EFR) of \\$n\\$ distinct positive integers \\$a\_{1} \< a\_{2} \< \dots \< a\_{n}\\$ such that $$ \sum\_{k=1}^{n} \frac{1}{a\_{k}} = 1. \tag{1} \label{1} $$

When \\$n=3\\$, for instance, we have $$ \frac{1}{2} + \frac{1}{3} + \frac{1}{6} = 1 \tag{2}\label{2}. $$

Note that the above EFR in \eqref{2} consists of two terms with prime denominators, and one term with a composite denominator.

Recently, I've come across an EFR of \\$1\\$ that solely consists of composite1 denominators. This is the following identity:

$$ \sum\_{k=1}^{\infty} \frac{1}{k(k+1)} = 1. \tag{3}\label{3} $$

However, this is not a *finite* EFR of \\$1\\$. I am interested EFRs of \\$1\\$ that are finite and solely consist of composite denominators.

## Task

Find an algorithm that, given \\$n\\$, does the following two things:

1. Determines whether an EFR of length \\$n\\$ exists without any prime denominators. If such a representation does not exist, the algorithm should print the output

> No EFR of \\$1\\$ with composite denominators exists for this \\$n\\$

or something else along along these lines - as long as it's clearly conveyed no such representation exists.

2. If such a representation *does* exist, the algorithm ought to output the denominators of at least one valid solution of length \\$n\\$. Alternatively, you may output a list of rational numbers which are unit fractions, but only if they are an exact representation of the value (so not floating-point -- see the paragraph on precision in this question).

## Test Cases

Below, I list one possible output for \\$n=9,\dots,13\\$, and the only possible output2 for \\$n=4\\$ and \\$n=8\\$. They were found by Neil and Mukundan314:

```
n     outputs
4     No EFR of 1 with composite denominators exists for this n
8     No EFR of 1 with composite denominators exists for this n
9     {4, 6, 8, 9, 10, 12, 15, 18, 24}
10    {4, 6, 8, 9, 10, 15, 18, 21, 24, 28}
11    {4, 6, 8, 10, 12, 15, 18, 20, 24, 30, 36}
12    {4, 8, 9, 10, 12, 15, 18, 20, 21, 24, 28, 30}
13    {4, 8, 9, 12, 14, 15, 18, 20, 21, 24, 28, 30, 35}

```

## Rules

We largely follow the rules described here:

* You may output the EFRs in any order, of you choose to output multiple. But all denominators *within* each EFR ought to be displayed in ascending order.
* If you choose to output all possible solutions, or a particular subset of them, you must not output duplicates. This includes lists which are the same under some permutation.
* You may assume \\$ n \\$ is a positive integer, and is not \\$ 2 \\$
* Your code does not need to practically handle very high \\$ n \\$, but it must work in theory for all \\$ n \\$ for which a solution exists
* You may use any standard I/O method
* Standard loopholes are forbidden
* The shortest code in bytes wins

---

**Notes**

\[1\] This infinite EFR actually does include a prime denominator, the number \\$2\\$, as pointed by Jonathan Allan. We can only say it includes no *odd* primes.

\[2\] For \\$n=2,\dots,8\\$, the output should indicate that no such EFR is possible, as the sum of the reciprocals of the composites up to that value of \\$n\\$ is less than \\$1\\$ -- this was (also) noted by Jonathan Allan.

# Answer
> 6 votes
# Jelly, 25 bytes

```
ḊẒÐḟœc³P-ƤS⁼PƲƇ
0Ç1#<?9ḢÇ

```

A full program that accepts an integer, \\$n\\$, and prints the Jelly representation of a list of at least one valid decomposition, each as a list of \\$n\\$ composite denominators in ascending order, or nothing if not possible (when \\$n \lt 9\\$).

**Try it online!** (Too slow for even \\$n=12\\$)

### How?

Brute force:

```
ḊẒÐḟœc³P-ƤS⁼PƲƇ - Link 1: integer, UpperBound
Ḋ               - dequeue {UpperBound} -> [2..UpperBound]
 ẒÐḟ            - discard primes
    œc³         - combinations of program input (n) items (without repeats)
              Ƈ - keep those for which:
             Ʋ  -   last four links as a monad - f(Selection):
        -Ƥ      -     for outfixes of length one less than Selection:
       P        -       product
          S     -     sum -> SumProducts
            P   -   product {Selection} -> TotalProduct
           ⁼    -   {SumProducts} equals {TotalProduct}?

0Ç1#<?9ḢÇ - Main Link: integer, N:
     ?    - if...
    < 9   - ...condition: {N} is less than 9?
0         - ...then: zero
  1#      - ...else: start with k=1 and increment collecting the first 1 for which:
 Ç        -            call Link 1 (empty list is falsey)
       Ḣ  - head -> k
        Ç - call Link 1
          - implicit print

```

---

## Original  ~~35~~  29 bytes

```
ḢH;2×S$;
_9µ‘Ṡ“ðØÐ€½µ®©¥‘xÇ⁸¡

```

A monadic Link that accepts an integer, \\$n\\$, and yields a valid decomposition as a list of \\$n\\$ composite denominators in descending order, or an empty list if not possible (when \\$n \lt 9\\$).

**Try it online!** (The numbers get huge pretty quickly!)

### How?

We know \\$n \lt 9\\$ is not possible since the sum of the reciprocals of the eight smallest composites is less than one: \\$\frac{1}{4} + \frac{1}{6} + \frac{1}{8} + \frac{1}{9} + \frac{1}{10} + \frac{1}{12} + \frac{1}{14} + \frac{1}{15} \lt 1\\$.

We can find a solution for \\$n=9\\$: `[4, 6, 8, 9, 10, 12, 15, 18, 24]`.

We can create a solution of length \\$n+1\\$ by removing the largest denominator, \\$D\\$, from a solution of length \\$n\\$ and replacing it by two larger numbers, \\$A\\$ and \\$B\\$, such that \\$\frac{1}{D} = \frac{1}{A} + \frac{1}{B}\\$.

\\$D\\$ is composite so we can factorise it as \\$D=F.M\\$ and now \\$A=F(F+M) \gt D\\$ and \\$B=M(F+M) \gt D\\$ will do:

\begin{align} \frac{1}{D} & = \frac{1}{FM} \\ & = \frac{F+M}{FM(F+M)} \\ & = \frac{M}{FM(F+M)} + \frac{F}{FM(F+M)} \\ & = \frac{1}{F(F+M)} + \frac{1}{M(F+M)} \\ \end{align}

Since the first \\$D\\$, \\$24\\$, is divisible by \\$4\\$ we can fix \\$F\\$ at \\$2\\$ safe in the knowledge that both \\$A\\$ and \\$B\\$ will be divisible by \\$4\\$ forever, allowing us to continue using \\$F=2\\$.

```
ḢH;2×S$; - Link 1: list of integers, Denominators (descending)
Ḣ        - remove the head and yield it
 H       - halve that -> M
  ;2     - concatenate a two -> [M,F]
      $  - last two links as a monad:
     S   -   sum them -> M+F
    ×    -   multiply -> [M(M+F), F(M+F)] = [max(A,B), min(A,B)]
       ; - concatenate {the beheaded Denominators}

_9µ‘Ṡ“ðØÐ€½µ®©¥‘xÇ⁸¡ - Link: integer, N
_9                   - subtract 9 -> N-9
  µ                  - start a new monadic Link ~ X=N-9
   ‘                 - increment {X}
    Ṡ                - sign -> S
     “ðØÐ€½µ®©¥‘     - [24, 18, 15, 12, 10, 9, 8, 6, 4]
                x    - repeat elements max(S,0) times
                         -> [] if N < 9 else [24, 18, 15, 12, 10, 9, 8, 6, 4]
                  Ç⁸¡ - call Link 1 min(0,X) times

```

# Answer
> 5 votes
# Charcoal, 56 bytes

```
Ｎθ¿›θ⁸«”)‴7⊘J‹ê%υZX”≔Ｅ⁻θ⁹×⁺⁸×³ι⁺¹¹×³ιζ⊞ζ⁻×⁹θ⁵⁷Ｗ⁻ζυ⊞υ⌊ιＩυ

```

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

```
Ｎθ¿›θ⁸«

```

Input `n` and check that it is greater than `8`.

```
”)‴7⊘J‹ê%υZX”

```

Output the first `8` terms of @Mukandan314's `9`-term sequence using a compressed string.

```
≔Ｅ⁻θ⁹×⁺⁸×³ι⁺¹¹×³ιζ⊞ζ⁻×⁹θ⁵⁷

```

Generate some more terms using the relation in my comment on the question (`b=8` and `c=3` in my case).

```
Ｗ⁻ζυ⊞υ⌊ιＩυ

```

Sort and output the remaining terms.

# Answer
> 4 votes
## JCram, 27 bytes (SBCS), 91 bytes JS

-5 thanks to Arnauld.

JavaScript solution:

```
n=>n<9?0:[4,6,8,9,10,12,15,18,...[...Array(n-9)].map(_=>x*(x+=3),x=8),x*3].sort((a,b)=>a-b)

```

Uses an idea pointed out by Neil and Mukundan314 in the comments.

JCrammed:

```
⌽⌊≥⍸χⒷ⁸d⊤¤β⁷D⏧¤⍆ξτ⍯⍇¯⌷3⊑¹⍤L

```

JCram is a research project on compressing JavaScript code for the purposes of code golf. Read more.

# Answer
> 3 votes
# Husk, 17 bytes

```
?øḟo=1ṁ\Ṗ¹fohpN<9

```

Try it online! (applied to all numbers up to 12, too slow for 13)

Not happy about how long the filter conditions ended up being, but working with infinite lists is always fun

### Explanation

```
?øḟo=1ṁ\Ṗ¹fohpN<9
?              <9    If the input is less than 9:
 ø                     Return an empty list
                     Else:
          fohpN        Get the infinite list of composite numbers
        Ṗ¹             Get all possible subsets of length `input` from this list
  ḟo                   Find the first one for which:
      ṁ\                 The sum of reciprocals
    =1                   Is equal to 1

```

# Answer
> 1 votes
# Python, 82 bytes

```
f=lambda x:x<9or(x<10)*b"	\n"or[*(a:=f(x-1))[:-1],b:=a[-1]+4,b//2*(b//2-2)]

```

Attempt This Online!

Works by splitting the largest denominator in the solution for `n - 1` using the relation provided by @Neil in the question's comments; with the solution for `n = 9` hardcoded in the bytestring.

# Python, 83 bytes

```
lambda x:x<9or sorted([*b"	\n",9*x-57]+[(i*3+8)*(i*3+11)for i in range(x-9)])

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 30 bytes

```
•š~ üõ•25вI9-DdiFD¨sθ;2sªDO*«ï

```

Try it online!

Returns a negative number for inputs \< 9

This is basically just a port of Jonathan Allan's original Jelly answer. He has a great description of the algorithm and why it works on his post.

```
•š~ üõ•25вI9-DdiFD¨sθ;2sªDO*«ï
•š~ üõ•25в                         push [4, 6, 8, 9, 10, 12, 15, 18, 24]
          I9-                      subtract 9 from the input
             Ddi                   if the value is positive:
                F                      Repeat (input - 9) times:
                 D¨sθ                      detach the tail
                     ;2sª                  prepend 2
                         DO*               calculate the two new denominators
                            «ï             re-attach to the head as ints
                                   implicit output

```

# Answer
> 1 votes
# PARI/GP, 83 bytes

A port of @Mukundan314's Python answer in PARI/GP .

---

83 bytes, It can be golfed more.

Attempt This Online!

```
f(x)={if(x<9,1,concat([4,6,8,9,10,12,15,18,9*x-57],vector(x-9,i,(3*i+5)*(3*i+8))))}

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 92 bytes

```
Do[x=Select[Subsets[Range@i~Select~CompositeQ,{#}],Tr[1/#]==1&];If[x!={},Return[x]],{i,#!}]&

```

Try it online!

Note: Tio times out for inputs 4 \< n \< 9 and n \> 13

Returns a list of solutions found, or returns nothing if no solution exists.

A brute force method for finding a solution. Mathematica doesn't have lazy evaluation lists so I have to use a loop to iterate over the bounds.

Breakdown of the function, which takes 1 input `n`

```
Do[                                            For i in [1...n!]
    x=Select[                                  Get all
        Subsets[                                 subsets of length n of
            Range@i~Select~CompositeQ,             the set of composite numbers < i
            {#}],
        Tr[1/#]==1&];                          For which the sum of their inverses is 1.
    If[x!={}, Return[x]],                      If one or more are found, return them
{i,#!}]&

```

# Answer
> 1 votes
# Scala 3, 96 bytes

```
x=>if(x<9)Seq(1)else Seq(4,6,8,9,10,12,15,18,9*x-57)++((1 to x-9).map(i=>(3*i+5)*(3*i+8)).toSeq)

```

Attempt This Online!

# Answer
> 1 votes
# APL(NARS), 97 chars

```
r←f w;k;t
r←⍬⋄→0×⍳8≥w⋄r←4 6 8 9 10 12 15 18 24
→3×⍳w=k←≢r⋄t←r[k]÷8⋄r[k]←t×t+8⋄r,←8×t+8⋄→2
r←r[⍋r]

```

10+37+43+7=97, It use the fact that `1/rs=(1/r(r+s))+(1/s(r+s))` test:

```
  f 8
┌0─┐
│ 0│
└~─┘
  f 9
┌9──────────────────────┐
│ 4 6 8 9 10 12 15 18 24│
└~──────────────────────┘
  f 10
┌10────────────────────────┐
│ 4 6 8 9 10 12 15 18 33 88│
└~─────────────────────────┘
  f 20
┌20────────────────────────────────────────────────────────────────────────┐
│ 4 6 8 9 10 12 15 18 33 209 513 728 945 1505 2193 3009 3953 5025 6225 7553│
└~─────────────────────────────────────────────────────────────────────────┘
  +/÷f 10
1
~
  +/÷f 20
1
~
  +/÷f 500
1
~

```

It is possible find one decomposition of one fraction in sum of elements of 1/d and d is not prime \> 2. Example 13r10

```
  +/ 1r4 1r6 1r8 1r9 1r10 1r12 1r14 1r15 1r16 1r18 1r20 1r21 1r22 1r36 1r70 1r80 1r99
13r10

```

The more big number I found was 14r10. 15r10 and 2 it seems are too much big for algo

```
  +/1r4 1r6 1r8 1r9 1r10 1r12 1r14 1r15 1r16 1r18 1r20 1r21 1r22 1r24 1r28 1r35 1r36 1r48 1r99
7r5

```

It is possible find one decomposition of one fraction in sum of elements of 1/d with d natural number (so d could be prime too) example 13r129

```
  +/1r11 1r129 1r473
13r129

```

---
Tags: code-golf, math, number-theory, rational-numbers
---